微信小程序获取地理位置
微信小程序开发中选择地理位置,就需要通过官方文档API去判断用户是否授权地理位置,用户开启授权后可直接获取地理位置,否则需要用户手动开启授权。下面是获取地理位置的相关方法:
//先判断用户是否授权获取地理位置
let that = this;
wx.getSetting({
success(res) {
if (res.authSetting['scope.userLocation'] == false) {//如果没有授权地理位置
wx.openSetting({
success(res) {
res.authSetting = {//打开授权位置页面,让用户自己开启
"scope.userLocation": true
}
}
})
} else {//用户开启授权后可直接获取地理位置
wx.authorize({
scope: 'scope.userLocation',
success() {
//获取位置后相关操作
that.getLocation();
}
})
}
}
})
**获取地理位置后操作**
getLocation: function () {
let that = this;
wx.getLocation({
type: 'gcj02', // 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于 wx.openLocation 的坐标
success(res) {
wx.chooseLocation({
success: function (res) {
// 返回的res:name(地理名称)、address(详细地址,包括省市区相关信息,可根据需要进行拆分)、latitude(纬度)、longitude(经度)
},
})
}
})
},