微信小程序中怎样获取当前城市位置及再次授权地理位置的代码实现
获取当前城市位置及再次授权地理位置的代码实现:
一、获取当前城市位置:
通过微信小程序的API获取当前的经纬度,再通过API将经纬度转换为城市名称,即可获取当前所在的城市位置。
1. 获取当前位置的经纬度
在小程序的JS代码中使用wx.getLocation()方法获取当前位置经纬度:
wx.getLocation({
type: 'gcj02', //默认为 wgs84 返回 gps 坐标,gcj02 返回可用于微信小程序的坐标
success (res) {
const latitude = res.latitude // 纬度
const longitude = res.longitude // 经度
const speed = res.speed // 速度
const accuracy = res.accuracy // 精度
}
})
2. 将经纬度转换为城市名称
当获取到经纬度时,我们可以通过微信API获取城市名称。使用微信API需要调用接口,可以使用微信提供的第三方sdk wx-sdk,如果当前小程序没有开通地理位置授权,则需再次授权。
wx-sdk使用方法:
1. 在目录下安装腾讯地图API wx-sdk
npm install wx-sdk --save
2. 在需要使用的页面中引入SDK:
import QQMapWX from "./path/to/qqmap-wx-jssdk.min.js"
3. 创建SDK实例
var qqmapsdk = new QQMapWX({
key: '' // 自己申请的接口Key
});
4. 使用SDK提供的接口
qqmapsdk.reverseGeocoder({
location: {
latitude: 39.984060,
longitude: 116.307520
},
success: function (res) {
console.log(res);
}
})
二、再次授权地理位置:
1. 检查当前小程序是否已授权获取地理位置
在小程序中使用wx.getSetting()方法可以获取当前小程序的权限设置信息,通过判断scope.userLocation的值是否为true,即可判断当前小程序是否已授权获取地理位置。
wx.getSetting({
success(res) {
console.log(res.authSetting)
// res.authSetting = {
// "scope.userInfo": true,
// "scope.userLocation": true,
// "scope.address": true,
// "scope.record": true,
// "scope.writePhotosAlbum": true
// }
}
})
2. 调用wx.authorize()方法再次授权
如果当前小程序未授权获取地理位置,可以在需要地理位置权限的页面中弹出授权弹窗,通过调用wx.authorize()方法实现授权:
wx.authorize({
scope: 'scope.userLocation',
success () {
//用户已经同意小程序使用定位功能,后续调用wx.getLocation()接口不会弹窗询问
wx.getLocation({
success: function(res) {},
})
},
fail () {
// 用户拒绝授权后,再次提示授权窗口,继续授权
wx.showModal({
title: '提示',
content: '请授权地理位置',
success: function (res) {
if (res.confirm) {
wx.openSetting({
success: (res) => {
if (res.authSetting["scope.userLocation"]) {
//授权成功
wx.getLocation({
success: function (res) {},
})
} else {
//授权失败
}
}
})
} else if (res.cancel) {
console.log('取消授权')
}
}
})
}
})
以上是获取当前城市位置及再次授权地理位置的代码实现。如果用户在小程序中需要使用十字定位标记或地图来标注位置,同时需要实时获取当前位置,可以使用wx.startLocationUpdateBackground()和wx.onLocationChange()实现。使用wx.startLocationUpdateBackground()可以在小程序后台持续获取用户的位置信息,使用wx.onLocationChange()可以在位置变化时及时更新页面的显示。
