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、返回结果如下:
效果图: