在小程序中,可以通过调用 wx.getLocation() 方法来获取用户的位置信息。该方法需要授权用户位置信息,因此需要先调用 wx.getSetting() 方法获取用户授权状态,若用户已经授权,则可以调用 wx.getLocation() 方法获取用户位置信息。
具体的步骤如下:
wx.getSetting({
success(res) {
if (!res.authSetting['scope.userLocation']) {
// 若用户未授权,则调用 wx.authorize() 方法请求授权
wx.authorize({
scope: 'scope.userLocation',
success() {
// 用户已授权,可以调用 wx.getLocation() 方法获取位置信息
wx.getLocation({
type: 'wgs84',
success(res) {
const latitude = res.latitude // 纬度
const longitude = res.longitude // 经度
}
})
}
})
} else {
// 用户已授权,可以直接调用 wx.getLocation() 方法获取位置信息
wx.getLocation({
type: 'wgs84',
success(res) {
const latitude = res.latitude // 纬度
const longitude = res.longitude // 经度
}
})
}
}
})
wx.getLocation({
type: 'wgs84',
success(res) {
const latitude = res.latitude // 纬度
const longitude = res.longitude // 经度
}
})
其中,type 参数表示坐标类型,可选值为 wgs84 和 gcj02。wgs84 表示 GPS 坐标,gcj02 表示国测局坐标(火星坐标),一般使用 gcj02 即可。
需要注意的是,获取用户位置信息需要用户授权,因此需要在用户同意授权后才能调用 wx.getLocation() 方法。同时,需要处理授权失败等异常情况,以保证程序的健壮性。