微信小程序-用户地理位置授权以及获取用户位置信息
微信小程序有个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
}
})
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南