1、去高德开放平台获取高德地图key
地址:https://lbs.amap.com/
![](https://img-blog.csdnimg.cn/20201223192929695.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNTc0MDc5,size_16,color_FFFFFF,t_70)
注意:这里一定要选择web端的key,不要选择web服务的key,否则拿不到数据
2、去项目中引入key,也就是cdn,在这里我们在src下面创建一个unti文件夹,然后在到文件夹下面创建一个名为unti.js的文件
![](https://img-blog.csdnimg.cn/20201223193453119.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNTc0MDc5,size_16,color_FFFFFF,t_70)
3、在unti.js中写入我们的方法封装
注意:这里之所以不在index.html中引入,是因为如果在index.html引入,汇报AMap not undefined或者是找不到
export default function MapLoader() {
let aMapScript = document.createElement('script')
aMapScript.setAttribute('src', 'https://webapi.amap.com/maps?v=1.4.11&key=c0af2a8bee25c16d7a307124ddb43056&plugin=AMap.CitySearch')
document.head.appendChild(aMapScript)
return aMapScript.onload = function() {
AMap.plugin('AMap.Geolocation', function() {
var geolocation = new AMap.Geolocation({
// 是否使用高精度定位,默认:true
enableHighAccuracy: true,
// 设置定位超时时间,默认:无穷大
timeout: 10000,
// 定位按钮的停靠位置的偏移量,默认:Pixel(10, 20)
buttonOffset: new AMap.Pixel(10, 20),
// 定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
zoomToAccuracy: true,
// 定位按钮的排放位置, RB表示右下
buttonPosition: 'RB'
})
geolocation.getCurrentPosition()
AMap.event.addListener(geolocation, 'complete', onComplete)
AMap.event.addListener(geolocation, 'error', onError)
function onComplete(data) {
// data是具体的定位信息
console.log(data)
console.log('123123')
}
function onError(data) {
console.log(data)
// 定位出错
console.log('123123s')
}
})
}
}
4、在需要引用的该方法
![](https://img-blog.csdnimg.cn/20201223193642260.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNTc0MDc5,size_16,color_FFFFFF,t_70)
5、打印结果
![](https://img-blog.csdnimg.cn/20201223193933709.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNTc0MDc5,size_16,color_FFFFFF,t_70)