步骤:
1 在pubic文件夹下的index.html中引入高德地图的js文件
<script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=自己申请的key&plugin=AMap.CitySearch"></script>
2 在methods中写一个获取位置的方法
getLngLatLocation() {
AMap.plugin('AMap.CitySearch', function () {
var citySearch = new AMap.CitySearch();
citySearch.getLocalCity(function (status, result) {
if (status === 'complete' && result.info === 'OK') {
// 查询成功,result即为当前所在城市信息
console.log('通过ip获取当前城市:', result)
//逆向地理编码
AMap.plugin('AMap.Geocoder', function () {
var geocoder = new AMap.Geocoder({
// city 指定进行编码查询的城市,支持传入城市名、adcode 和 citycode
city: result.adcode
})
var lnglat = result.rectangle.split(';')[0].split(',');
geocoder.getAddress(lnglat, function (status, data) {
if (status === 'complete' && data.info === 'OK') {
// result为对应的地理位置详细信息
console.log(data)
}
})
})
}
})
})
}
3 mounted中调用。
结果报错:AMap is not defined
以下是网上的常用几种方法:
1 把<script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=自己申请的key&plugin=AMap.CitySearch"></script>放到body中,结果依旧报这个错
2 把eslintrc.js文件中加入
"globals": {
"AMap": "true",
"AMapUI":"true"
},
测试结果:没什么暖用
摸索了很久,终于找打了解决这个问题的办法:
异步回调(以下是正确的解法)
--------------------------------------------------------------------------------------------------
1 导出一个函数,动态加载(导出函数的目的是为了方便其他地方也用到)
export const amap=function(key){
return new Promise(resolve=>{
let url=`https://webapi.amap.com/maps?v=2.0&key=${key}&plugin=AMap.CitySearch&callback=AMapLoad`
let script=document.createElement("script");
script.src=url;
document.body.appendChild(script);
window.AMapLoad=function(){
resolve(window.AMap)
}
})
}
2 在需要用到的页面的mounted里执行这个函数
amap("申请的key的值").then((amap) => {
this.getCityLoaction(amap); //这个amap就是高德的地图对象Map
});
3 在methods中写获取城市信息的具体逻辑
methods:{
getCityLoaction(MAP) {
var citysearch = new MAP.CitySearch();
citysearch.getLocalCity((status, result) => {
if (status === "complete" && result.info === "OK") {
if (result && result.city && result.bounds) {
var cityinfo = result.city;
var citybounds = result.bounds;
this.curCity = result.city;
console.log("当前城市", result);
}
} else {
this.curCity = "全部";
}
});
},
}
以上即可解决这个问题