Vue使用BMap获取当前ip的省市及天气温度 !

1安装BMap

npm install bmap

2、安装axios

npm install axios --save

3、在min.js中全局引入

import axios from 'axios'
Vue.prototype.$axios = axios

4、在项目public文件 index.html中添加以下代码:

下注:text 是 申请秘钥时候的应用名称 ,javascript:类型

           ak 是自己注册秘钥 (搜索:百度地图ak秘钥申请有教程)

<script
      type="text/javascript"
      src="http://api.map.baidu.com/api?v=2.0&ak=0BRaoaAC99dmv6sXfQDnMY0LPYGGxOWM"
></script>

5、在vue.config.js文件configureWebpack中加入以下代码

   externals: {
      BMap: "BMap", // 百度地图配置
    },

6、在utile下创建一个getUserLocation.js的文件引入BMap并写以下代码

// 获取当前城市
import BMap from "BMap";
const getCurrentCityName = function () {
  return new Promise((resolve, reject) => {
    let myCity = new BMap.LocalCity();
    myCity.get(
      (result) => {
        let geoc = new BMap.Geocoder();
        geoc.getLocation(result.center, (rs) => {
          // rs 中携带着所有的定位信息,这里只获取了城市(city)和所在的区(district)
          let addComp = rs.addressComponents;
          let result = addComp.city;
          resolve(result);
          console.log(reject);
        });
      },
      { enableHighAccuracy: true }
    );
  });
};
export default getCurrentCityName;

7、在vue页面中引用

import getCurrentCityName from "@/utils/getUserLocation";

8、html代码

 <div style="color: #d1f0ff">
       <p style="margin-bottom: 0.2rem">{{ weather }}</p>
       <p v-if="lower" class="fz14">{{ lower }}~{{ higher }}℃</p>
 </div>

9、js代码

      下注:city=411321是当前地区身份证前六位

<script>

 data() {
   weather: '',
   lower: "",
   higher: '',
 },
 mounted() {
     this.getCurrentCity();//获取当前城市天气
  }
 getCurrentCity() {
      //获取城市
      getCurrentCityName().then((city) => {
        this.LocationMsg = city;
        // console.log(city);
        this.getWeather();
      });
    },
    getWeather() {
      //云南迪庆维西傈僳族自治县533423 上海浦东310115  河南南召411321
      // http://wthrcdn.etouch.cn/weather_mini?city=" + this.LocationMsg 失效
      // https://way.jd.com/he/freeweather?city=beijing&appkey=APPKEY 天气接口地址,需要在vue.config.js中配置
      //获取天气
      this.$axios.get("https://restapi.amap.com/v3/weather/weatherInfo?key=fe90a1458920f7dde0cfffd6223ccd92&city=411321&extensions=all").then((res) => {
        console.log(res);
        this.weather = res.data.forecasts[0].casts[0].dayweather ? res.data.forecasts[0].casts[0].dayweather : "晴";
        this.lower = res.data.forecasts[0].casts[0].nighttemp;
        this.higher = res.data.forecasts[0].casts[0].daytemp;
      })
        .catch(function (error) {
          console.log(error);
        });
},

</script>

 5、返回结果如下:

 

 效果图:

完毕!

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值