1、获取用户当前的设置(判断授权状态)
使用wx.getSetting接口
获取用户的当前设置。返回值中会出现小程序已经向用户请求过的权限。
然后我们去判断用户地理位置的授权状态,根据状态做相应的操作
具体实现方式如下
getUserLocation: function () {
var _this=this
wx.getSetting({
success (res) {
console.log(res.authSetting)//会返回用户授权的结果
//scope.userLocation参数表示的是地理位置授权状态
// undefined-初始化进入该页面/false-非初始化进入该页面,且未授权/true-地理位置授权
let locationStatus=res.authSetting['scope.userLocation']
if (locationStatus != undefined && locationStatus != true) {
//未授权
wx.showModal({
title: '请求授权当前位置',
content: '需要获取您的地理位置,请确认授权',
success: function (res) {
if (res.cancel) {
//取消授权
wx.showToast({
title: '拒绝授权',
icon: 'none',
duration: 1000
})
} else if (res.confirm) {
//用户拒接授权后,通过wx.openSetting重新发起授权请求
wx.openSetting({
success: function (res) {
if (locationStatus == true) {
wx.showToast({
title: '授权成功',
icon: 'success',
duration: 1000
})
//再次授权,调用wx.getLocation的API
_this.getLocation();
} else {
wx.showToast({
title: '授权失败',
icon: 'none',
duration: 1000
})
}
}
})
}
}
})
} else if (locationStatus == undefined) {
//用户首次进入页面,调用wx.getLocation的API
_this.getLocation();
} else {
console.log('授权成功')
//调用wx.getLocation的API
_this.getLocation();
}
}
})
}
2、调取微信接口拿到位置经纬度
getLocation: function () {
let that = this;
wx.getLocation({ //拿到经纬度
type: 'gcj02',
//type参数默认为wgs84返回 gps 坐标,gcj02 返回可用于 wx.openLocation 的坐标
success: function (res) {
var latitude = res.latitude //纬度,范围为 -90~90,负数表示南纬
var longitude = res.longitude //经度,范围为 -180~180,负数表示西经
console.log("经纬度:latitude " + latitude + " ;longitude " + longitude) //这里获取的是经纬度坐标
that.getLocal(latitude, longitude) //把经纬度传给getLocal方法
},
fail: function (res) {
console.log('fail ' + JSON.stringify(res))
}
})
},
在获取定位后,如果是在微信开发者工具中进行调试,会发现获取到的定位不够精确。按照官方的回复是工具上用的是模拟使用IP定位,而且只支持gcj02 坐标,会存在一定的误差。而且在实际的测试中发现gcj02会比wgs84会精确一些,所以建议使用gcj02
3、通过经纬度获取具体位置
我们已经拿到了用户的经纬度,我这里通过腾讯位置服务把经纬度转换成具体的地理位置(当然也可以通过百度或者高德等,逻辑都一样的)
首先需要获取腾讯位置服务的开发者秘钥然后下载微信小程序的javaScriptSDK文件
接下来引入sdk文件通过腾讯获取具体位置
var QQMapWX = require('./utils/qqmap-wx-jssdk.js');//引入SDK文件
var qqmapsdk;
onLaunch: function () {
qqmapsdk = new QQMapWX({//创建实例
//腾讯位置服务: https://lbs.qq.com/console/mykey.html
key: '' //这里自己的key秘钥进行填充,该key是腾讯位置服务中申请的
});
that.getUserLocation()
}
// 获取当前地理位置
getLocal: function (latitude, longitude) { //把经纬度转换成地理位置
let that = this;
qqmapsdk.reverseGeocoder({//使用腾讯位置服务的API传入经纬度
location: {
latitude: latitude,
longitude: longitude
},
success: function (res) {
let province = res.result.ad_info.province
let city = res.result.ad_info.city
let address=res.result.address
console.log("province:"+province,"city:"+city,"address:"+address);
//就可以得到具体的省市区及详细位置
that.globalData.userInfo.province = province
that.globalData.userInfo.city = city
that.globalData.userInfo.address = address
that.globalData.userInfo.latitude = latitude
that.globalData.userInfo.longitude = longitude
}
});
},