uniapp 在h5和小程式上使用高德獲取使用者城市位置
阿新 • • 發佈:2020-07-23
- 開發文件 https://lbs.amap.com/api
- 錯誤狀態 https://lbs.amap.com/api/webservice/guide/tools/info/
- 雖然用的高德但是你還需要申請一個騰訊地圖的key來使用getLocation API
- https://uniapp.dcloud.io/collocation/manifest?id=h5sdkconfig
import amap from '@/static/lib/amap-wx.js'; // 只能用於小程式 const amap_wx_key = '<微信key>'; const amap_h5_key = '<Web服務key>'; let _key = ''; // #ifdef H5 _key = amap_h5_key uni.getLocation({ success: function(pos) { uni.request({ method: 'GET', url: 'https://restapi.amap.com/v3/geocode/regeo', data: { key: _key, location: `${pos.longitude},${pos.latitude}`, poitype: '城市', }, success: ({ data }) => { const city = data.regeocode.addressComponent.city commit('setCity', city) res(city); }, fail: r => { console.log(r); } }); } }); // #endif // #ifdef MP-WEIXIN _key = amap_wx_key this.amapPlugin = new amap.AMapWX({ key: _key }); this.amapPlugin.getRegeo({ success: data => { const city = data[0].regeocodeData.addressComponent.city; commit('setCity', city) res(city); }, fail(e) { console.error(e); uni.showModal({ title: e.errCode, content: e.errMsg, }) } }); // #endif