1.获取签名,调用微信api进行位置信息授权获取当前经纬度
2.火星经纬度转百度经纬度
3.利用百度api转化成对应的省市区详细地址(这里要注意,我们需要引入百度api,及自己的密钥,<script type="text/javascript" src="//api.map.baidu.com/api?v=3.0&ak=自己的密钥"></script>)
wxAddress() {
let that = this;
let u = navigator.userAgent;
let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //g
let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
let request_url = ''
if (isAndroid) {
this.isIOS = false;
request_url = encodeURIComponent(location.href);
}
if (isIOS) {
this.isIOS = true;
request_url = encodeURIComponent(window.entryUrl);//这里是解决ios路由不刷新,获取签名失败的问题,具体使用见最后
}
let params = {
url: request_url
}
let url = this.GLOBAL.API_WECHATLOGIN_GET_WECHAT_SIGN;//签名接口
this.$post(url, params).then((res) => {
if (res.data.retCode == 200) {
that.resulted = res.data.data;
that.wx.config({ //配置微信接口
debug: false,
appId: that.resulted.appId,
timestamp: that.resulted.timestamp,
nonceStr: that.resulted.noncestr,
signature: that.resulted.signature,
jsApiList: [ // 所有要调用的 API 都要加到这个列表中,要调用的微信接口
'getLocation'
]
});
that.wx.ready(function () {
that.wx.getLocation({
type: 'gcj02', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
success: function(res) {
// that.latitude = res.latitude;
// that.longitude = res.longitude;
//火星经纬度转百度地图经纬度
let x_PI = 3.14159265358979324 * 3000.0 / 180.0;
var lat =Number(res.latitude);
var lng =Number(res.longitude);
var z =Math.sqrt(lng * lng + lat * lat) +0.00002 * Math.sin(lat * x_PI);
var theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_PI);
that.longitude = z*Math.cos(theta) + 0.0065;
that.latitude = z*Math.sin(theta) + 0.006;
that.detailAddress();
},
fail: function(err) {
that.Toast({
message: err,
position: 'center',
duration: 2000
})
}
});
});
that.wx.error(function (res) {
that.Toast({
message: res,
position: 'center',
duration: 5000
})
});
} else {
that.Toast({
message: res.data.message,
position: 'center',
duration: 5000
})
}
})
},
detailAddress(){
let that=this;
let point = new BMap.Point(that.longitude, that.latitude)
let gc = new BMap.Geocoder()
gc.getLocation(point, function(rs){
let addComp = rs.addressComponents
let province = addComp.province
let city = addComp.city
let district = addComp.district
let street = addComp.street
console.log(rs.addressComponents)
that.address=province+city+district+street
console.log(that.address)
})
},
解决ios路由不刷新,获取签名失败的问题:
router.afterEach((to, from) => {// true 时 为 IOS 设备
if (window.__wxjs_is_wkwebview) { // IOS
if (window.entryUrl == '' || window.entryUrl == undefined) { //记录该地址config配置时使用
if (process.env.NODE_ENV == 'development') {
var url = `http://m1.baidu.com${to.fullPath}`
} else if (process.env.NODE_ENV == 'production') {
var url = `http://m2.baidu.com${to.fullPath}`
}
window.entryUrl = url
}
}
})