微信公众号开发文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115
高德文档:https://lbs.amap.com/api/javascript-api/reference-amap-ui/other/positionpicker
需求:如果是浏览器打开项目的话就是用高德获取定位,如果是微信打开的话就是用微信定位获取经纬度
1-1.获取当前定位信息
AMap.plugin(['AMap.Geolocation'], ()=> {
const geolocation = new AMap.Geolocation({timeout: 10000});
map.addControl(geolocation);
geolocation.getCurrentPosition( (status, result) =>{
if (status == 'complete') {
onComplete(result)
} else {
onError(result)
}
});
})
1-2. 根据经纬度获取定位信息
function getWGSLocation(locationarg){ // 传入经纬度,格式:`${longitude},${latitude}`
return new Promise(function(resolve, reject){
AMap.convertFrom(locationarg,
"gps",
(status, result) => { // WGS84 转高德
if (status.toLowerCase() === 'complete' && result.info.toLowerCase() === 'ok') {
const lon = result.locations[0].getLng();
const lat = result.locations[0].getLat();
geocoder.getAddress([lon, lat],
(s, r) => {
if (s.toLowerCase() === 'complete' && r.info.toLowerCase() === 'ok') {
resolve(r)
} else {
console.log('error');
}
});
} else {
console.log('error');
}
});
})
}
2-1.配置wx.config(为了安全,所有信息要从服务端获取)
import wx from 'weixin-jsapi'; //npm安装weixin-jsapi 或者直接页面引用
// 通过后端的接口拿到appid,签名...等信息,注:当前页面的href不可以有#,否去取不到
axios.post('/Home/GetWxJsSdkParam', {url:location.href.split('#')[0]}).then((response) => {
const c = res;
wx.config({
beta: true,// 必须这么写,否则wx.invoke调用形式的jsapi会有问题
// debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: c.AppId, // 必填,企业号的唯一标识,此处填写企业号corpid
timestamp: c.TimeStamp, // 必填,生成签名的时间戳
nonceStr: c.NonceStr, // 必填,生成签名的随机串
signature: c.Sign,// 必填,签名,见附录1
jsApiList: ['getLocation'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
})
2-2.获取当前位置的经纬度,然后根据微信返回的经纬度,调用上面高德地图的1-2的getWGSLocation方法
const that = this;
wx.getLocation({
type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
success: function (res) {
console.log(res)
const latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
const longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
// `${longitude},${latitude}`
getWGSLocation(longitude+','+latitude).then((r)=>{
console.log(r);// 获取的具体位置信息;
})
},
fail:function(err){
console.log('微信调用失败哦');
console.log(err);
}
});