Table of Contents
Step 1 - Set up the environment and gather all resources
Step 2 - Start with index.html
Step 3 - Set up the index text
Step 4 - Get the Weather API and Unsplash API Key
Step 5 - Start with JavaScript Coding
第 6 步 - 免费托管您的网站!
Home Web Front-end JS Tutorial Tutorial: How to make a weather web application using JS and API (Collection)

Tutorial: How to make a weather web application using JS and API (Collection)

Sep 15, 2021 pm 12:12 PM
css html js

In the previous article "Teach you how to use HTML, CSS and JS to make a random password generator (share)", I introduced you how to use html, css and js to make a random password. Password Generator. The following article will introduce to you how to use JS and API to make a weather web application. Let's see how to do it together.

Tutorial: How to make a weather web application using JS and API (Collection)

Today I will make a great weather app where we can search for any city, region or country and use Weather API Get its current weather. Additionally, to add some polish to it, I also used the Unsplash API as the background image for the site, which will be based on the location you enter. I added a tilt effect and a glassy look to the card. The programming languages ​​we will use in this project are HTML, CSS, and JS. So let's goo goo goo.

Look at the final look we will achieve

Demo address: https://wanghao221.github.io/Weather.io/

bilibili show video: https://www.bilibili.com/video/BV1xX4y1c7Z4

Note: I only mentioned a few in the article that you should/might use in your code Key points and steps. Since, this is a blog, not a code base, I want to keep it simple. If you want to refer to the entire code address https://github.com/wanghao221/Weather.io, go take a look!

Step 1 - Set up the environment and gather all resources

Using your favorite code editor, create a new application called "Weather App" or whatever you want desired name, then create these three files and add these resources to the folder:

  • index.html

  • style. css

  • script.js

Other resources we need:

  • Favicon

  • Loading GIF (optional)

  • Vanilla-Tilt.js file

Download all of them Resource address: https://download.csdn.net/download/qq_44273429/20463321

Step 2 - Start with index.html

Start with a common template for HTML files. Add a title if desired.

Before linking style.css and script.js, link the Google fonts you want. I have used the Poppins font, which is one of my favorite fonts. (Google Fonts)

HTML

<link
href="https://fonts.googleapis.com/css2family=Poppins:ital,wght@0,200;0,400;0,500;0,600;0,700;0,800;0,900;1,800&display=swap"
rel="stylesheet">
Copy after login

Now starting with body if you wish to add a loader to your website then you can add it to the body tag , and then write a script for it.

HTML

<body onload="myFunction()">
Copy after login

Make two separate divs. One for the heading title and one for the card. Add appropriate div tag below it.

Here I use a search button in SVG format. You can use this code for buttons in card div.

HTML

<button>
<svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 16 16" height="1em"
width="1.5em" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M10.442 10.442a1 1 0 011.415 0l3.85 3.85a1 1 0 01-1.414 1.415l-3.85-3.85a1 1 0 010-1.415z"
clip-rule="evenodd"></path>
<path fill-rule="evenodd" d="M6.5 12a5.5 5.5 0 100-11 5.5 5.5 0 000 11zM13 6.5a6.5 6.5 0 11-13 0 6.5 6.5 0 0113 0z"
clip-rule="evenodd"></path>
</svg>
</button>
Copy after login

Add weather icon to default icon display.

HTML

<div class="flex">
  <img class="icon lazy"  src="/static/imghw/default1.png"  data-src="https://openweathermap.org/img/wn/04d.png"   alt=""  />
  <div class="description">多云</div>
</div>
Copy after login

Loading animation and Vanilla-Tilt js script. Add it before the end of the text. I added the Vanilla-Tilt Js files to the resources mentioned in step 1 above.

JS

<script>
        var preloader = document.getElementById(&#39;loading&#39;);
        function myFunction() {
            preloader.style.display = &#39;none&#39;;
        }
</script>
<script type="text/javascript" src="js/vanilla-tilt.js"></script>
    <script type="text/javascript">
        VanillaTilt.init(document.querySelector(".card"), {
            max: 15,
            glare: true,
            reverse: true,
            "max-glare": 0.5,
            speed: 400
        });
        VanillaTilt.init(document.querySelectorAll(".card"));
</script>
Copy after login

Step 3 - Set up the index text

Start with the style body and other elements.

Set the style of loading animation. You can style it using this code. Since the loading animation has a white background, I used #fff. I added the SVG image in the resources folder.

CSS

#loading{
  position: fixed;
  width: 100%;
  height: 100vh;
  background: #fff url(&#39;/loading.svg&#39;)
  no-repeat center;
  z-index: 99999;
}
Copy after login

Please refer to the Github repository for CSS code

Address: https://github.com/wanghao221/Weather.io

Step 4 - Get the Weather API and Unsplash API Key

Go to OpenWeatherMap and create an account. After logging in, click in the API Keys tab and you will see the API key. Copy the API Key and paste it in the second line of the JavaScript code mentioned below (apiKey: " <Insert API Key here>",)

Tutorial: How to make a weather web application using JS and API (Collection)Go to Unsplash Source. Here you can see how images can be recalled in different ways based on size, text, user preferences, favorites, etc.

Tutorial: How to make a weather web application using JS and API (Collection)

Step 5 - Start with JavaScript Coding

Integrate in JavaSciptAPIFor learning how to Web It is crucial that the application uses API. I've listed the entire code. You can go through it and understand the code.

我已将此调用"url(&#39;https://source.unsplash.com/1600x900/?city " + name + "&#39;)"用于背景图像。您可以根据需要自定义URL

我还使用了上海市的默认天气weather.fetchWeather("Shanghai");。您可以在此处添加任何城市的名称。每当您加载网站时,都会弹出这个城市的天气。

JS

let weather = {
  apiKey: "<Insert API Key here>",
  fetchWeather: function (city) {
    fetch(
      "https://api.openweathermap.org/data/2.5/weather?q=" +
        city +
        "&units=metric&appid=" +
        this.apiKey
    )
      .then((response) => response.json())
      .then((data) => this.displayWeather(data));
  },
  displayWeather: function (data) {
    const { name } = data;
    const { icon, description } = data.weather[0];
    const { temp, humidity } = data.main;
    const { speed } = data.wind;
    document.querySelector(".city").innerText = "Weather in " + name;
    document.querySelector(".icon").src =
      "https://openweathermap.org/img/wn/" + icon + ".png";
    document.querySelector(".description").innerText = description;
    document.querySelector(".temp").innerText = temp + "°C";
    document.querySelector(".humidity").innerText =
      "湿度: " + humidity + "%";
    document.querySelector(".wind").innerText =
      "风速: " + speed + " km/h";
    document.querySelector(".weather").classList.remove("loading");
    document.body.style.backgroundImage =
      "url(&#39;https://source.unsplash.com/1600x900/?city " + name + "&#39;)";
    document.body.style.backgroundRepeat = "none";
    document.body.style.backgroundSize = "100";
    document.body.style.width = "100%";
    document.body.style.height = "100%";
    document.body.style.backgroundRepeat = "no-repeat";
    document.body.style.backgroundSize = "cover";

  },
  search: function () {
    this.fetchWeather(document.querySelector(".search-bar").value);
  },
};

document.querySelector(".search button").addEventListener("click", function () {
  weather.search();
});

document
  .querySelector(".search-bar")
  .addEventListener("keyup", function (event) {
    if (event.key == "Enter") {
      weather.search();
    }
  });

weather.fetchWeather("Shanghai");
Copy after login

第 6 步 - 免费托管您的网站!

现在,当您完成编码后,您可以在您的网站上托管您自己的天气应用程序,或者您甚至可以在 Github 上免费托管它!!!

https://github.com/wanghao221/Weather.io

托管是可选的,但我建议将其发布并与您的朋友和家人共享,并将其添加到您的项目列表中。

即将推出的功能

这是我计划添加一些更酷的功能,例如

每当您打开网站时进行位置检测,它将显示其天气特定位置的相关天气新闻使背景图像更准确地显示位置使其对大多数设备(iPad 和平板电脑)的响应速度更快

项目中一些很酷的截图

Tutorial: How to make a weather web application using JS and API (Collection)

Tutorial: How to make a weather web application using JS and API (Collection)

Tutorial: How to make a weather web application using JS and API (Collection)

推荐学习:HTML/CSS视频教程JS视频教程

The above is the detailed content of Tutorial: How to make a weather web application using JS and API (Collection). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

How to write split lines on bootstrap How to write split lines on bootstrap Apr 07, 2025 pm 03:12 PM

There are two ways to create a Bootstrap split line: using the tag, which creates a horizontal split line. Use the CSS border property to create custom style split lines.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

How to set up the framework for bootstrap How to set up the framework for bootstrap Apr 07, 2025 pm 03:27 PM

To set up the Bootstrap framework, you need to follow these steps: 1. Reference the Bootstrap file via CDN; 2. Download and host the file on your own server; 3. Include the Bootstrap file in HTML; 4. Compile Sass/Less as needed; 5. Import a custom file (optional). Once setup is complete, you can use Bootstrap's grid systems, components, and styles to create responsive websites and applications.

How to insert pictures on bootstrap How to insert pictures on bootstrap Apr 07, 2025 pm 03:30 PM

There are several ways to insert images in Bootstrap: insert images directly, using the HTML img tag. With the Bootstrap image component, you can provide responsive images and more styles. Set the image size, use the img-fluid class to make the image adaptable. Set the border, using the img-bordered class. Set the rounded corners and use the img-rounded class. Set the shadow, use the shadow class. Resize and position the image, using CSS style. Using the background image, use the background-image CSS property.

How to use bootstrap button How to use bootstrap button Apr 07, 2025 pm 03:09 PM

How to use the Bootstrap button? Introduce Bootstrap CSS to create button elements and add Bootstrap button class to add button text

See all articles