话不多说看代码
- 申请高德地图key(console.amap.com/dev/key/app)
- 下载小程序的SDK(lbs.amap.com/api/wx/down…);tip:不能放到static目录下
- 在APP.vue写一下方法
import AmapFile from '@/utils/amap-wx.js'; // 小程序sdk文件 export default { onLaunch: function(e) { // #ifdef H5 this.loadScrpit(); // #endif // #ifdef MP-WEIXIN this.xcx_mapInit(); // #endif }, onShow: function() { //这里不一定用setTimeou。可以使用其他异步处理 // #ifdef H5 setTimeout(() => { this.mapInit(); }, 2000); // #endif }, methods: { loadScrpit() { let script = document.createElement('script'); script.src = 'https://webapi.amap.com/maps?v=1.4.15&key=自己申请的key'; document.body.appendChild(script); }, // h5定位 mapInit() { const mapObj = new AMap.Map('iCenter'); mapObj.plugin('AMap.Geolocation', function() { const geolocation = new AMap.Geolocation({ enableHighAccuracy: false, //是否使用高精度定位,默认:true timeout: 5000 //超过5秒后停止定位,默认:无穷大 }); mapObj.addControl(geolocation); geolocation.getCurrentPosition(); //返回定位信息 AMap.event.addListener(geolocation, 'complete', function(res) { console.log(res); }); //返回定位出错信息 AMap.event.addListener(geolocation, 'error', function(err) { console.log(err); }); }); }, // 小程序定位 xcx_mapInit() { const myAmapFun = new AmapFile.AMapWX({ key: '申请的key' }); myAmapFun.getPoiAround({ success: function(data) { const markersData = data.markers; }, fail: function(info) { wx.showModal({ title: info.errMsg }); } }); } } } }