微信小程序有個bug,一旦用戶拒絕獲取地理位置信息后,重新進入小程序不會再彈出提示框獲取用戶信息,只有在設置里面允許獲取地理位置信息
onLoad: function () {
var that = this
wx.getSetting({
success: (res) => {
// res.authSetting['scope.userLocation'] undefined-表示初始化進入該頁面 false-表示非初始化進入該頁面,且未授權
if (res.authSetting['scope.userLocation'] != true) {
wx.authorize({
scope: 'scope.userLocation',
success() {
that.getLocation()
},
fail: function(error) {
wx.showModal({
title: '提示',
content: '您未開啟保定位權限,請點擊確定去開啟權限!',
success(res) {
if (res.confirm) {
wx.openSetting()
}
},
fail: function() {
wx.showToast({
title: '未獲取定位權限,請重新打開設置',
icon: 'none',
duration: 2000
})
})
}
})
}else {
that.getLocation()
}
}
})
},
getLocation: function(){
const that = this
var i = setInterval(function() {
wx.getLocation({
type: 'gcj02', // 默認為 wgs84 返回 gps 坐標,gcj02 返回可用於 wx.openLocation 的坐標
success: function(res) {
that.setData({
latitude: res.latitude,
longitude: res.longitude,
})
var longitude = res.longitude
var latitude = res.latitude
that.loadCity(longitude, latitude)
clearInterval(i)
},
fail: function() {
wx.showToast({
title: '手機定位未打開',
icon: 'none',
duration: 2000
})
},
complete: function() {
// complete
}
})
}, 2000)
},
loadCity: function(longitude, latitude) {
var that = this
//請求的地址是騰訊地圖,參考文檔https://lbs.qq.com/service/webService/webServiceGuide/webServiceOverview
wx.request({
url:'https://apis.map.qq.com/ws/geocoder/v1/?location='+latitude + ','+longitude +'&key=SSSBZ-SQZK6-U3XSL-EPA5P-6VNK6-ANF4P&get_poi=1',
data: {},
header: {
'Content-Type': 'application/json'
},
success: function(res) {
const data = res.data
app.globalData.location = data.result.address_component
var location = data.result.address
that.setData({
location: location
});
},
fail: function() {
console.log("失敗")
},
complete: function() {
// complete
}
})
}