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
}
}
})