前提要求:
1.准备高德地图平台的账号,申请key
(1)key类型:微信小程序
(2)key类型:web服务
2.引入amap-wx.js文件,通过下方链接下载,解压获得js文件
import amap from '@/common/amap-wx.130.js';
3.判断浏览器
uni.showLoading({
title: '请稍后...'
});
let en = window.navigator.userAgent.toLowerCase();
// 匹配en中是否含有MicroMessenger字符串
if(en.match(/HUAWEI/i) == 'huawei' || en.match(/HONOR/i) == 'honor') {
this.getSuc(); // 华为手机比较特殊,在获取地方上,所以特殊处理,给直通
} else if (en.match(/MicroMessenger/i) == 'micromessenger') {
this.getWXLocation() //微信内置浏览器
} else {
this.getAreas() //其他浏览器
}
一、微信浏览器
// 微信内置浏览器
async getAmapL() {
const amapPlugin = new amap.AMapWX({
key: 'cb208c51c75f062c327dfc98a62f3726'//高德API key类型:微信小程序
})
return new Promise(async (resolve,reject) => {
await amapPlugin.getRegeo({
success: (data) => {
resolve({longitude: data[0].longitude, latitude: data[0].latitude})
},
fail: (err) => {
reject(err)
}
})
})
},
async getWXLocation() {
let res = this.getAmapL();
setTimeout(()=> {
this.promiseState(res).then(state =>{
if(state == 'pending') {
this.status = 3 // 判断当前状态 华为手机
uni.hideLoading();
} else {
res.then(res => {
if(res) {
// 拿到经纬度
this.getSignin(res.longitude, res.latitude)
} else {
this.status = 3
}
})
}
});
},4500)
},
获取promiseState,根据结果定时判断
promiseState(promise) {
const target = {}
return Promise.race([promise, target]).then(
value => (value === target) ? 'pending' : 'fulfilled',
() => 'rejected',
)
},
二、其他浏览器
// 获取经纬度
async getL() {
return new Promise((resolve,reject) => {
uni.getLocation({
type:'wgs84', // 'gcj02','wgs84'
success: (res) => {
resolve({longitude: res.longitude, latitude: res.latitude})
},
fail: (e) => {
reject(e)
}
})
})
},
async getAreas() {
let res = this.getL();
setTimeout(()=> {
this.promiseState(res).then(state =>{
if(state == 'pending') {
this.status = 3
uni.hideLoading();
} else {
res.then(res => {
if(res) {
this.getSignin(res.longitude, res.latitude)
} else {
this.status = 3
}
})
}
});
},4500)
},
三、逆编码-经纬度转地址
// 逆编码
turnAdrr(longs, lat) {
// 高德逆地理变码 https://lbs.amap.com/api/webservice/guide/api/georegeo/
let _key = 'a862c1e523fd7d228285fd52bfcf21f9'; //高德API key类型:web服务
uni.request({
method: 'GET',
url: 'https://restapi.amap.com/v3/geocode/regeo?parameters',
data: {
key: _key,
location: `${longs},${lat}`,
output: 'JSON'
},
success: (res) => {
uni.showModal({
title: '提示-地址',
content: JSON.stringify(res),
success: function() {}
});
},
fail: r => {
console.log(r);
}
});
},