小程序onLocationChange接口的使用及注意事项

功能描述
监听实时地理位置变化事件,需结合 wx.startLocationUpdateBackground、wx.startLocationUpdate使用。

申请开通最好使用 微信小程序主体类型:工具 服务查询

参数:
function callback
实时地理位置变化事件的回调函数

参数
Object res
属性 类型 说明 最低版本
latitude number 纬度,范围为 -90~90,负数表示南纬。使用 gcj02 国测局坐标系
longitude number 经度,范围为 -180~180,负数表示西经。使用 gcj02 国测局坐标系
speed number 速度,单位 m/s
accuracy number 位置的精确度
altitude number 高度,单位 m 1.2.0
verticalAccuracy number 垂直精度,单位 m(Android 无法获取,返回 0) 1.2.0
horizontalAccuracy number 水平精度,单位 m 1.2.0

示例代码:

const _locationChangeFn = function(res) {
console.log('location change', res)
}
wx.onLocationChange(_locationChangeFn)
wx.offLocationChange(_locationChangeFn)

首先需要请求权限,看看用户是否已经授权过位置权限,如果有权限则开始监听,没有则需要通过authorize接口授权位置

wx.getSetting({
success(res) {
if(!that.data.addressName){
wx.showLoading({
title: '位置获取中',
})
}
if (!res.authSetting['scope.userLocation']) {
wx.authorize({
scope: 'scope.userLocation',
success () {
if(!that.data.addressName){
wx.startLocationUpdate({
success(res){
console.log(res);
}
})
}
}
})
}else{
if(!that.data.addressName){
wx.startLocationUpdate({
success(res){
console.log(res);
}
})
}
}
}
})
//监听位置权限开启
wx.onLocationChange((res)=>{
var latitude = res.latitude,
longitude = res.longitude;
wx.request({
url: 'https://apis.map.qq.com/ws/geocoder/v1/?location='+latitude+','+longitude+'&get_poi=0&key=JMRBZ-44B6K-4P5JR-AWIVT-6PDB5-EFB5G',
success(res){
that.recommend(res.data.result.address_component.province);
that.setData({
addressName: res.data.result.address_component.province,
city: res.data.result.address_component.city,
district: res.data.result.address_component.district
})
wx.stopLocationUpdate({
success(res){
console.log(res);
console.log('位置监听已经关闭');
}
})
}
})
})
posted @   Dreams_log  阅读(3492)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示