html+js,配合百度地图及和风天气实现动态天气预报页面

功能实现:浏览器通过经纬度定位获取经纬度,再使用和风天气提供的api通过经纬度获取城市信息及天气信息,然后进行数据渲染,图标使用的是skycons.js库。

html代码如下

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>H5 | 和风天气</title>
    <!-- icon引入和风天气的图标作为页面标题边上的图标 -->
    <link
      rel="icon"
      href="https://cdn.qweather.com/img/plugin/190516/icon/logo/favicon.ico?v=20201022"
      type="image/x-icon"
    />
    <script
    type="text/javascript"
    src="https://api.map.baidu.com/api?v=2.0&ak=7a6QKaIilZftIMmKGAFLG7QT1GLfIncg"
  ></script>
    <!-- 定期刷新页面,这里是100秒刷新一次(注释掉了,有需要的自行开启) -->
    <!-- <meta http-equiv="refresh" content="100"> -->
    <!-- 引入图标等的js文件(官方的) -->
    <script src="app.js"></script>
    <link rel="stylesheet" href="app.css" />
    <!-- 引入汉字转拼音的js文件 -->
    <!-- 更新之后用不到了——2023.7.8 -->
    <!-- <script src="Convert_Pinyin.js"></script> -->
  </head>

  <body>
    <h1>正在定位……(建议Edge或者火狐测试,谷歌经纬度定位不准确)</h1>
    <div class="box" id="mybox"></div>
    <div class="home" id="mycons"></div>
    <div id="he-plugin-h5"></div>
    <!-- 在js中创建元素并引入到这里面 -->
    <script>
      WIDGET = {};
    </script>
  </body>

  <script>
    var h1 = document.querySelector("h1");
    var mybox = document.querySelector("#mybox");
    var mycons = document.querySelector("#mycons");
    getLocation();
    function getLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          function success(position) {
            // console.log("经度:" + position.coords.latitude);
            // console.log("纬度:" + position.coords.longitude);
            if (position.coords.latitude == undefined) {
              setTimeout(() => {
                getLocation();
              }, 500);
            } else {
              getLocation2(position.coords.latitude, position.coords.longitude);
            }
          },
          function fail(error) {
            switch (error.code) {
              case error.PERMISSION_DENIED:
                console.log("用户拒绝对获取地理位置的请求。");
                break;
              case error.POSITION_UNAVAILABLE:
                console.log("位置信息是不可用的。");
                break;
              case error.TIMEOUT:
                console.log("请求用户地理位置超时。");
                break;
              case error.UNKNOWN_ERROR:
                console.log("未知错误。");
                break;
            }
          },
          { enableHighAcuracy: false }
        );
      } else {
        console.log("Geolocation is not supported by this browser.");
      }
    }
    // 运行 getLocation2() 函数
    function getLocation2(aaa, bbb) {
      // 百度地图的初始化
      var geolocation = new BMap.Geolocation();
      geolocation.getCurrentPosition(function (e) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
          h1.style.display = "none";
          // 百度 geolocation 的经纬度属性不同,此处是 point.lat 而不是 coords.latitude
          var city = e.address.city.substr(0, e.address.city.length - 1);
          // var city_PY = pinyin.getFullChars(city).toString().toLowerCase();
          // console.log(aaa, bbb);
          var a = aaa.toFixed(2);
          var b = bbb.toFixed(2);
          var url = `https://devapi.qweather.com/v7/weather/now?location=${b},${a}&key=cde03782fab84225bf2a93be5a2cfe7b`;
          var url2 = `https://geoapi.qweather.com/v2/city/lookup?location=${b},${a}&key=cde03782fab84225bf2a93be5a2cfe7b`;
          var location;
          fetch(url2, {
            method: "get",
            mode: "cors",
          })
            .then(function (data) {
              return data.json();
            })
            .then(function (data) {
              location = `${data.location[0].adm1}-${data.location[0].adm2}-${data.location[0].name}`;
              fetch(url, {
                method: "get",
                mode: "cors",
              })
                .then(function (data) {
                  return data.json();
                })
                .then(function (data) {
                  mybox.innerHTML = `
                                <canvas id=icon1 width="100" height="100"></canvas>
                                <p class="area" id="myarea">${location}</p>
                                <p>
                                    <span>${data.now.text}</span>
                                    <span>${data.now.temp}℃(实时)</span>
                                </p>
                            `;
                  changeWeather(data.now.icon, "icon1");
                });
            });

          var url3 = `https://devapi.qweather.com/v7/weather/7d?location=${b},${a}&key=cde03782fab84225bf2a93be5a2cfe7b`;
          fetch(url3, {
            method: "get",
            mode: "cors",
          })
            .then(function (data) {
              return data.json();
            })
            .then(function (data) {
              // console.log(data);
              mycons.innerHTML = `
                            <div class="line">
                                <div class="icon">
                                    <p class="day">${data.daily[1].fxDate}</p>
                                    <canvas id="icon2" width="60" height="60"></canvas>
                                    <p>${data.daily[1].tempMin}/${data.daily[0].tempMax}℃</p>
                                </div>
                                <div class="icon">
                                    <p class="day">${data.daily[2].fxDate}</p>
                                    <canvas id="icon3" width="60" height="60"></canvas>
                                    <p>${data.daily[2].tempMin}/${data.daily[0].tempMax}℃</p>
                                </div>
                                <div class="icon">
                                    <p class="day">${data.daily[3].fxDate}</p>
                                    <canvas id="icon4" width="60" height="60"></canvas>
                                    <p>${data.daily[3].tempMin}/${data.daily[0].tempMax}℃</p>
                                </div>
                            </div>
                            <div class="line">
                                <div class="icon">
                                    <p class="day">${data.daily[4].fxDate}</p>
                                    <canvas id="icon5" width="60" height="60"></canvas>
                                    <p>${data.daily[4].tempMin}/${data.daily[0].tempMax}℃</p>
                                </div>
                                <div class="icon">
                                    <p class="day">${data.daily[5].fxDate}</p>
                                    <canvas id="icon6" width="60" height="60"></canvas>
                                    <p>${data.daily[5].tempMin}/${data.daily[0].tempMax}℃</p>
                                </div>
                                <div class="icon">
                                    <p class="day">${data.daily[6].fxDate}</p>
                                    <canvas id="icon7" width="60" height="60"></canvas>
                                    <p>${data.daily[6].tempMin}/${data.daily[0].tempMax}℃</p>
                                </div>
                            </div>
                        `;
              changeWeather(data.daily[1].iconDay, "icon2");
              changeWeather(data.daily[2].iconDay, "icon3");
              changeWeather(data.daily[3].iconDay, "icon4");
              changeWeather(data.daily[4].iconDay, "icon5");
              changeWeather(data.daily[5].iconDay, "icon6");
              changeWeather(data.daily[6].iconDay, "icon7");
            });

          function changeWeather(code, box) {
            let skycons = new Skycons({
              color: "white",
            });
            if (code == 100) {
              skycons.add(box, Skycons.CLEAR_DAY);
              skycons.play();
            } else if (code >= 101 && code <= 104) {
              skycons.add(box, Skycons.CLOUDY);
              skycons.play();
            } else if (code >= 300 && code <= 399) {
              skycons.add(box, Skycons.RAIN);
              skycons.play();
            } else if (code >= 404 && code <= 406) {
              skycons.add(box, Skycons.SLEET);
              skycons.play();
            } else if (
              (code >= 400 && code <= 403) ||
              (code >= 407 && code <= 499)
            ) {
              skycons.add(box, Skycons.SNOW);
              skycons.play();
            } else if (code >= 200 && code <= 213) {
              skycons.add(box, Skycons.WIND);
              skycons.play();
            } else if (code >= 500) {
              skycons.add(box, Skycons.FOG);
              skycons.play();
            }
          }
        } else {
          alert("无法定位,请刷新页面");
        }
      });
    }
  </script>
</html>

案例中引用的 和风天气API后面的key值 是本人的,如果要另作他用的话,自己去官网申请,然后替换掉
和风天气申请key

由于俩js文件和一个css样式文件代码量太多,这里就存在我的网盘里了,自取!
链接:https://pan.baidu.com/s/10uPnrv8fEqhl26sbnscXvA
提取码:asdf

总结(方法步骤)

1、复制上面的的html代码到自己的html文件里(建议那俩引入的API后面的ak和key换成自己申请的)
2、自取网盘里的三个文件
3、自己的html文件和下载下来的css+js文件夹放在同一路径
4、运行html文件

很初级,我都感觉,有点啰嗦。。。不过,谁都是从初级过来的嘛,我认为,一个项目或程序的教程,起码得先让别人跑起来吧,然后调试修改啥的自己慢慢琢磨慢慢尝试就行。

  • 8
    点赞
  • 56
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
好的,我可以为您提供一个基于和天气API的Vue天气预报示例。 首先,您需要在和天气官网注册并创建一个应用,以获取访问API的key。 然后,您可以创建一个Vue项目,并安装axios和vue-axios插件来进行API请求。 接下来,您可以在Vue组件中编写代码来获取天气数据并渲染到页面上。以下是示例代码: ```html <template> <div class="weather"> <h1>{{ city }}天气预报</h1> <div v-if="loading">加载中...</div> <div v-else> <div>当前温度:{{ temperature }}℃</div> <div>天气状况:{{ weather }}</div> <div>向:{{ windDirection }}</div> <div>力:{{ windLevel }}</div> <div>湿度:{{ humidity }}%</div> </div> </div> </template> <script> import axios from 'axios'; import VueAxios from 'vue-axios'; export default { data() { return { city: '北京', loading: true, temperature: null, weather: null, windDirection: null, windLevel: null, humidity: null } }, mounted() { this.getWeather(); }, methods: { getWeather() { const key = 'YOUR_API_KEY'; const url = `https://free-api.heweather.net/s6/weather/now?location=${this.city}&key=${key}`; this.$http.get(url).then(response => { const data = response.data.HeWeather6[0].now; this.temperature = data.tmp; this.weather = data.cond_txt; this.windDirection = data.wind_dir; this.windLevel = data.wind_sc; this.humidity = data.hum; this.loading = false; }).catch(error => { console.log(error); }); } }, plugins: [ VueAxios, axios ] } </script> <style> .weather { text-align: center; } </style> ``` 在上面的代码中,您需要将`YOUR_API_KEY`替换为您的和天气API key,并将`city`设置为您想要获取天气的城市名称。 最后,您可以在Vue根实例中引入该组件并将其渲染到页面上。 ```html <template> <div id="app"> <weather></weather> </div> </template> <script> import Weather from './components/Weather.vue'; export default { components: { Weather } } </script> ``` 这样,您就可以在Vue中使用和天气API来获取天气预报了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

z_yuyu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值