前端实现天气预报

598 阅读1分钟

平时经常百度天气情况,于是给自己的博客做了一个获取天气预报的功能

大体步骤是先配置高德地图,申请一个服务编码。然后先调用高德的定位接口获取用户所在城市,在根据城市去查天气预报接口获得数据;

一:配置高德地图

先访问高德官网:高德控制台,注册后申请应用,获取key值。

这个key值可以通用高德提供的所有服务接口,比如定位、天气、路线规划、关键字搜索等。

二:访问接口

1、具体接口文档如下:

定位接口:IP定位-API文档| 高德地图API

天气预报接口:天气查询-API文档 | 高德地图API

2、代码实现较简单,大致如下

GetLocation(getWeathData);

function GetLocation(func) {
    let that = this,
      locationCookie = this.getSQCookie('sunqBlogLocation'),
      sunqBlogLocationCode = this.getSQCookie('sunqBlogLocationCode');

    // 如果用户多次访问,一周内不会重复请求定位接口
    if(locationCookie){
      func(locationCookie,sunqBlogLocationCode);
    }else {
      axios({
        url: 'https://restapi.amap.com/v3/ip',
        method: 'post',
        params: {
          key: 'ba5f9b69f0541123a4dbe142da230b4d'
        },
      }).then(function (resp) {
        func(resp.data.city,resp.data.adcode);
        that.setSQCookie('sunqBlogLocation',resp.data.city,3); // 相隔3小时同一浏览器再次访问时会重新定位
        that.setSQCookie('sunqBlogLocationCode',resp.data.adcode,3);
      }).catch();
    }
  };

function getWeathData(cityName, cityCode) {
      let that = this;
      axios({
        url: "https://restapi.amap.com/v3/weather/weatherInfo",
        method: "GET",
        params: {
          key: "ba5f9b69f0541123a4dbe142da230b4d",
          city: cityCode,
          extensions: 'all',
          output: "JSON"
        },
      }).then(function (resp) {
          //  此处获得天气预报数据
          console.log(resp.data);

          that.setSQCookie(
            "sunqBlogWeather",
            resp.data,
            3
          ); // 相隔3小时同一浏览器再次访问时会重新获取天气
        })
        .catch();
    }

三:效果演示

页面右侧组件:孙权的博客

详细代码:Github地址