获取地理位置请求免费天气接口

需求:根据地理位置信息去请求免费的天气接口数据,拿到数据后进行展示,这边我用到了俩个key,一个是高德天气的key和心知天气的key,为什么要这么麻烦呢,是因为之前写过一版不需要获取地理位置,直接就可以请求天气获取数据,但是用了不到一个月,崩了,要我用升级版...,所以还是就麻烦一点吧。

结果得到效果如下图

1.高德天气key需要注册开发者,在控制台申请

1.高德天气获取key

控制台点击应用管理==》我的应用==》创建应用如下图,名称随意填,类型选择出行

点击添加key

如下填写就行,得到了key

 

 2.心知天气获取key

心知天气右上角注册登录后,点击右上角控制台,进入后会让你选产品==》选择免费就行,选好如下:

 点击产品管理,得到公钥和私钥,复制私钥的key就行

 3.请求地理位置接口获取数据请求天气接口完整代码

<template>
  <div class="box">
    <p class="boxTemperature">{
   
   { weatcherData.tem }}°</p>
    <p class="boxWeather">{
   
   { weatcherData.wea }}</p>
    <p class="boxCity">{
   
   { weatcherData.city }}市</p>
  </div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      weatcherData: {
        tem: "",
        wea: "",
        city: ""
      },
      ipV: "",
      city: ""
    };
  },
  //生命周期 - 挂载完成(可以访问DOM元素)
  mounted() {
    this.gettianiq();
  },
  methods: {
    gettianiq() {
      axios({
        url: "/ws/location/v1/ip", //接口地址(代理把起码路径去掉)
        params: { key: "高德地图的位置key", output: "jsonp" }, //参数格式必须用到output传参为jsonp,否则会报跨域问题
      //   responseType: "jsonp" //跨域,必须用到jsonp
      }).then(res => {
        var ip = res.data.replace("QQmap&&QQmap(", "").replace(");", "");
        this.ipV = JSON.parse(ip);
        let {result}=this.ipV;

           this.city=result.ad_info.city;
           console.log(this.city,this.ipV.result);
           this.$nextTick(()=>{
            this.weather()
           })

      });
    },
    weather() {
      axios({
        url: "https://api.seniverse.com/v3/weather/now.json", //接口地址(代理把起码路径去掉)
        params: { key: "天气的私钥", location: this.city, unit: "c" } //参数格式必须用到
      }).then(res => {
        let { data } = res;
        console.log(data, "获取到数据");
        let { results } = data;
        this.weatcherData.tem = results[0].now.temperature;
        this.weatcherData.wea = results[0].now.text;
        this.weatcherData.city = results[0].location.name;
        console.log(results[0].now.temperature);
      });
    }
  }
};
</script>

<style scoped>
.box {
  display: flex;
  align-items: center;
  color: #5e5757;
  margin-right: 20px;
}
.boxTemperature {
  font-size: 18px;
}
.boxWeather {
  font-size: 14px;
  margin: 0 0 0 15px;
}
.boxCity {
  margin-left: 10px;
  font-size: 16px;
}
</style>

4.代理问题

直接请求直接出现跨域问题,解决方法如下:

1.在vue.config.js的devServer下配置proxy代理跨域

module.exports = {
  devServer: {
    // 反向代理配置
    proxy: {
      '/ws': {
        target: 'https://apis.map.qq.com/',
        ws: true,
        changOrigin: true,//允许跨域
        pathRewrite: {
          '^/ws': '/ws'
        }
      },
    }
  },
}

5.数据实现

高德接口得到的位置信息如下,把city提出来去请求天气接口了

天气接口得到的数据格式如下

 这样就实现啦,文章到此结束,希望对你有所帮助~

猜你喜欢

转载自blog.csdn.net/qq_44278289/article/details/131203545