微信小程序开发获取用户位置、腾讯内置地图
实际业务中经常会遇到获取当前位置或打开地图选择位置等需求,今天来聊聊如何在微信小程序中获取用户位置、内置地图选坐标和根据坐标在地图中打开。先看下内置地图的效果

使用了wx.getLocation、wx.chooseLocation、wx.openLocation三个方法,我们依次来看下:
wx.getLocation:获取当前的地理位置、速度,目前仅支持 gcj02 坐标,gcj02 是国测局坐标系,wgs84 为 gps 坐标系。
wx.getLocation({type: 'wgs84',success (res) {const latitude = res.latitude//纬度,范围为 -90~90,负数表示南纬const longitude = res.longitude//经度,范围为 -180~180,负数表示西经const speed = res.speed//速度,单位 m/sconst accuracy = res.accuracy}})
wx.chooseLocation:打开内置地图选择位置,返回选择的经度纬度坐标和位置名称等信息
wx.chooseLocation({success (res) {const latitude = res.latitude//纬度,范围为 -90~90,负数表示南纬const longitude = res.longitude//经度,范围为 -180~180,负数表示西经const name = res.name//位置名称const address = res.address//详细地址}})
wx.openLocation:使用微信内置地图查看位置,主要传入参数为维度、经度、缩放比例等
wx.getLocation({type: 'gcj02', //返回可以用于wx.openLocation的经纬度success (res) {const latitude = res.latitudeconst longitude = res.longitudewx.openLocation({latitude,longitude,scale: 18})}})
注意: 要用真机调试,而且开始前先要在app.json里配置permission,不然会出现

permission配置如下:
"permission": {"scope.userLocation": {"desc": "小程序请求授权您的地理位置信息"}}

然后建几个按钮,点击事件里分别执行这三个方法看下执行效果。
示例预览

说下一个常见场景,用户不允许授权地理位置信息,在后续操作中又需要授权才能使用地图。这种情况就利用查看当前设置判断用户授权信息,方法为:wx.getSetting获取用户当前设置,示例代码如下:
// 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.record" 这个 scopewx.getSetting({success(res) {if (!res.authSetting['scope.record']) {wx.authorize({scope: 'scope.record',success() {// 用户已经同意小程序使用录音功能,后续调用 wx.startRecord 接口不会弹窗询问wx.RecorderManager().start()}})}}})
所以用户点了不允许授权后,又要提示用户授权的功能可以参考如下代码:
onChooseLocation: function () {let self = this;wx.getSetting({success: (res) => {if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] == true) {self.setData({position: true,})//获取当前位置self.handleChooseLocation();} else {//未授权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 (res.authSetting["scope.userLocation"] == true) {// wx.showToast({// title: '授权成功',// icon: 'success',// duration: 1000// })//再次授权,调用wx.getLocation的APIself.handleChooseLocation();} else {// wx.showToast({// title: '授权失败',// icon: 'none',// duration: 1000// })}}})}}})}},fail(res) {console.log(res)}})},
如果未授权则弹出框执行效果如图:

THE END






