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

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 中添加以下代码

大家好,我是讯享网,很高兴认识大家。

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=是当前地区身份证前六位

<script> data() { weather: '', lower: "", higher: '', }, mounted() { this.getCurrentCity();//获取当前城市天气 } getCurrentCity() { //获取城市 getCurrentCityName().then((city) => { this.LocationMsg = city; // console.log(city); this.getWeather(); }); }, getWeather() { //云南迪庆维西傈僳族自治县 上海浦东 河南南召 // 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=fe90af7dde0cfffd6223ccd92&city=&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、返回结果如下:

 

 效果图:

完毕!

小讯
上一篇 2025-03-07 18:59
下一篇 2025-02-25 18:37

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/92567.html