如上图
从最新的微信小程序开发文档中查阅,通过微信小程序接口 wx.getLocation() 依然不能够直接获取到用户具体城市信息。本文写的主要是如何通过从微信API获取的经纬度信息转化为具体的城市街道信息。
首先如果开发者想要获取用户当前的位置,地理信息等,需要先在app.json中配置permission字段,如果用wepy开发的话,需在app.wpy做相应的配置:如下
permission: {
"scope.userLocation": {
"desc": "你的位置信息将用于小程序位置接口的效果展示"
}
第二步:进入页面,调用wx.getSetting拿到用户的授权情况。
第三步:调用wx.getLocation API 获取返回的经纬度,速度等信息
第四步:因为微信没有将经纬度直接转换为地理位置,因此这里需要通过借助微信位置服务,或者百度地图开放平台的全球逆地址编码。(这里本人利用的是百度开放平台,这里ak码是需要向百度地图开放平台获取的~,请求时填入相应的ak码,经纬度等信息。
第五步:用户进入页面的时候,可在页面的onShow方法中执行wx.getLocation让用户进行相应的授权,以后每次进入该页面时,通过wx.getSetting接口,返回用户授权具体信息。
具体代码如下:
onShow() {
this._getUserLocation();
}
_getUserLocation () {
var self = this
wx.getSetting({
success: (res) => {
console.log('用户授权情况', res)
//未授权
if(res.authSetting['scope.userLocation'] !== undefined &&
res.authSetting['scope.userLocation'] !== true) {
wx.showModal({
title: '请求授权当前位置',
content: '需要获取您的地理位置,请确认授权',
success: function (res) {
console.log(res)
if(res.cancel){
wx.showToast({
title: '拒绝授权',
icon: 'none',
duration: 1000
})
} else if (res.confirm) { //确认授权, 通过wx.openSetting发起授权请求
wx.openSetting({
success: function (res) {
if(res.authSetting["scope.userLocation"] == true) {
wx.showModal({
title: '授权成功',
icon: 'success',
duration: 1000
})
self._getCityLocation()
} else {
wx.showModal({
title: '授权失败',
icon: 'none',
duration: 1000
})
}
}
})
}
}
})
} else if (res.authSetting['scope.userLocation'] == undefined) {
self._getCityLocation()
console.log('这个为undefined')
} else {
console.log('授权成功')
self._getCityLocation()
}
}
})
}
_getCityLocation(){
let self = this
wx.getLocation({
type: 'wgx84',
success: (res) => {
let latitude = res.latitude
let longitude = res.longitude
let speed = res.speed
wx.request({
url: 'http://api.map.baidu.com/geocoder/v2/?ak=Vh0ALNzHjjEm5RP0Ie16dlBhZbdEQip9&location=' + res.latitude + ',' + res.longitude + '&output=json',
data: {},
header: { 'Content-type': 'application/json' },
success: function (ops){
console.log(ops)
self.address = ops.data.result.addressComponent.city +
ops.data.result.addressComponent.district
},
fail: function (resq) {
wx.showModal({
title: '信息提示',
content: '请求失败',
showCancel: false,
confirmColor: '#f37938'
});
}
})
},
fail: (res) => {
wx.showModal({
title: '信息提示',
content: '请求失败',
showCancel: false,
comfirmColor: '#f37938'
})
}
})
}
效果如下
用户首次进入页面时会先先请求用户授权地理位置权限
用户拒绝授权后
用户拒绝授权后再次进入该页面:
用户同意授权后: