search
HomeWeb Front-endJS TutorialTutorial: How to make a weather web application using JS and API (Collection)

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">

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()">

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>

Add weather icon to default icon display.

HTML

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

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>

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;
}

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>",</insert>)

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('https://source.unsplash.com/1600x900/?city " + name + "')"用于背景图像。您可以根据需要自定义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");

第 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
This article is reproduced at:掘金. If there is any infringement, please contact admin@php.cn delete
HTML超文本标记语言--超在那里?(文档分析)HTML超文本标记语言--超在那里?(文档分析)Aug 02, 2022 pm 06:04 PM

本篇文章带大家了解一下HTML(超文本标记语言),介绍一下HTML的本质,HTML文档的结构、HTML文档的基本标签和图像标签、列表、表格标签、媒体元素、表单,希望对大家有所帮助!

html和css算编程语言吗html和css算编程语言吗Sep 21, 2022 pm 04:09 PM

不算。html是一种用来告知浏览器如何组织页面的标记语言,而CSS是一种用来表现HTML或XML等文件样式的样式设计语言;html和css不具备很强的逻辑性和流程控制功能,缺乏灵活性,且html和css不能按照人类的设计对一件工作进行重复的循环,直至得到让人类满意的答案。

web前端笔试题库之HTML篇web前端笔试题库之HTML篇Apr 21, 2022 am 11:56 AM

总结了一些web前端面试(笔试)题分享给大家,本篇文章就先给大家分享HTML部分的笔试题(附答案),大家可以自己做做,看看能答对几个!

HTML5中画布标签是什么HTML5中画布标签是什么May 18, 2022 pm 04:55 PM

HTML5中画布标签是“<canvas>”。canvas标签用于图形的绘制,它只是一个矩形的图形容器,绘制图形必须通过脚本(通常是JavaScript)来完成;开发者可利用多种js方法来在canvas中绘制路径、盒、圆、字符以及添加图像等。

总结HTML中a标签的使用方法及跳转方式总结HTML中a标签的使用方法及跳转方式Aug 05, 2022 am 09:18 AM

本文给大家总结介绍a标签使用方法和跳转方式,希望对大家有所帮助!

html5废弃了哪个列表标签html5废弃了哪个列表标签Jun 01, 2022 pm 06:32 PM

html5废弃了dir列表标签。dir标签被用来定义目录列表,一般和li标签配合使用,在dir标签对中通过li标签来设置列表项,语法“<dir><li>列表项值</li>...</dir>”。HTML5已经不支持dir,可使用ul标签取代。

html中document是什么html中document是什么Jun 17, 2022 pm 04:18 PM

在html中,document是文档对象的意思,代表浏览器窗口的文档;document对象是window对象的子对象,所以可通过“window.document”属性对其进行访问,每个载入浏览器的HTML文档都会成为Document对象。

html5支持boolean值属性吗html5支持boolean值属性吗Apr 22, 2022 pm 04:56 PM

html5支持boolean值属性;boolean值属性指是属性值为true或者false的属性,如input元素中的disabled属性,不使用该属性表示值为flase,不禁用元素,使用该属性可以不设置属性值表示值为true,禁用元素。

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment