微信小程序关于位置location(一)

2,210 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第5天,点击查看活动详情

微信小程序获取精确的地理位置,使用wx.getLocationwx.onLocationChangewx.startLocationUpdate,需要用户授权scope.userLocationwx.startLocationUpdateBackground方法,需要用户授权scope.userLocationBackground

wx.getLocation

获取当前的地理位置,离开小程序后,接口无法调用,开启高精度定位,接口耗时会增加。其中地图相关使用的坐标格式应为 gcj02,默认是wgs84(gps 坐标)。

  • 当使用第三方服务进行逆地址解析的时候,需要注意第三方服务默认的坐标系。
  • 开发者工具中定位模拟使用 IP 定位,存在一定误差。开发者工具只支持 gcj02 坐标。

getLocation调用频率限制

当小程序频繁调用wx.getLocation接口会导致用户手机电量消耗较快,如需频繁调用需要改为wx.onLocationChange(持续定位接口)。

wx.getLocation({
 type: 'gcj02',
 success (res) {
   const latitude = res.latitude
   const longitude = res.longitude
   const accuracy = res.accuracy
 }
})

wx.onLocationChange

监听实时地理位置变化事件,使用的时候,需要开启进入前后台均接受位置消息。使用wx.startLocationUpdateBackground方法。该方法需要用户授权(scope.userLocationBackground)。授权成功,小程序才能在前后台一直接受位置消息变化。 使用wx.startLocationUpdate方法,开启小程序进入前台时接收位置消息。需要授权(scope.userLocation)。

wx.onLocationChange();
wx.offLocationChange();

微信小程序获取获取模糊地理位置,wx.getFuzzyLocation方法,需要用户授权scope.userFuzzyLocation

wx.getFuzzyLocation

获取模糊地理位置,返回的是经过模糊处理的经纬度坐标,支持返回 wgs84 或 gcj02 两种类型的坐标,需要用户授权 scope.userFuzzyLocation。

配置规则

使用地理位置的接口,需要在app.json中配置规则

image.png

注意:

  1. 获取精确位置和模糊位置是互斥的。否则会出现错误