参考网址:
https://blog.csdn.net/YY110621/article/details/87921605
https://blog.csdn.net/weixin_49210760/article/details/110147651
实现效果:
准备工作:
一申请高德地图的key和安全密钥教程
一申请高德地图逆地理编码key
第一步:在 public 文件夹下的 index.html 中引入:
<!--
获取地理位置
AMap.Geolocation是将要用到的高德插件
-->
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=8875f135d1964134aa2131d7ceacc133&AMap.Geolocation"></script>
第二步:安装高德地图的库,在 main.js 文件中写上这些代码
import VueAMap from "vue-amap";//引入高德地图
Vue.use(VueAMap)//挂在到Vue实例上
// 初始化vue-amap
VueAMap.initAMapApiLoader({
// 高德的key
key: "自己申请的key值",
// 插件集合
plugin: [
"AMap.Autocomplete",
"AMap.PlaceSearch",
"AMap.Scale",
"AMap.OverView",
"AMap.ToolBar",
"AMap.MapType",
"AMap.PolyEditor",
"AMap.CircleEditor",
"AMap.Geolocation",
"Geocoder",
],
// 高德 sdk 版本,默认为 1.4.4
v: "1.4.4",
});
//高德的安全密钥
window._AMapSecurityConfig = {
securityJsCode: "自己申请的安全密钥",
};
第三步:在 src 文件夹下创建一个 utils 文件夹后再创建一个 location.js 文件,代码如下:
/**
* 高德地图定位
* @type {{}}
*/
export const location = {
initMap(id){
let mapObj = new AMap.Map(id, {})
let geolocation;
mapObj.plugin(['AMap.Geolocation'], function () {
geolocation = new AMap.Geolocation({
enableHighAccuracy: true, // 是否使用高精度定位,默认:true
timeout: 10000, // 超过10秒后停止定位,默认:无穷大
maximumAge: 0, // 定位结果缓存0毫秒,默认:0
convert: true, // 自动偏移坐标,偏移后的坐标为高德坐标,默认:true
showButton: true, // 显示定位按钮,默认:true
buttonPosition: 'LB', // 定位按钮停靠位置,默认:'LB',左下角
buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
showMarker: true, // 定位成功后在定位到的位置显示点标记,默认:true
showCircle: true, // 定位成功后用圆圈表示定位精度范围,默认:true
panToLocation: true, // 定位成功后将定位到的位置作为地图中心点,默认:true
zoomToAccuracy: true // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
})
mapObj.addControl(geolocation)
geolocation.getCurrentPosition()
})
return geolocation;
}
}
第四步:在需要用到的页面引入你创建的这个js文件
import { location } from '../../utils/location'
第五步:在需要用到的页面引入引入 axios 库(需提前安装:npm install axios -S)
用原生axios进行数据请求的目的:为了不和项目脚手架配置的axios根路径起冲突,因为当前脚手架封装的axios根路径定死了,虽然可以配置不同的根路径,但是俺不知道怎么配置,就只能用最原始的方法请求数据。拿到当前位置的经纬度后需要调用高德地图的 逆地理编码api(lbs.amap.com/api/webserv… 接口从而获取咱中国平民老百姓看得懂的地址
import axios from 'axios'
第六步:在需要用到的页面中定义一个 address 数据,获取到地址后赋值以便在页面上渲染出来
data(){
return {
address:null,//渲染到页面上的地址,随便放到页面的哪里,只要能看到就行,双括号渲染
}
}
第七步:在需要用到的页面中定义一个 getLocation 方法,并在 mounted 生命周期函数中调用。
mounted(){
this.getLocation()
},
methods: {
/**获取地图定位*/
getLocation() {
let geolocation = location.initMap("map-container"); //定位
AMap.event.addListener(geolocation, "complete", result => {
axios({
method: 'GET',
url: 'https://restapi.amap.com/v3/geocode/regeo',
params: {
key:'自己逆地理编码的id',
location:result.position.lng + ',' + result.position.lat//经纬度
}
}).then(res=>{
this.address = res.data.regeocode.formatted_address
})
});
}
},
第八步:用火狐浏览器调试,每次点击允许就可以了,不用勾选“记住次决定”,因为谷歌浏览器不会弹出获取地址的弹窗