微信小程序API~地理位置location

(1)使用微信内置地图查看位置

wx.openLocation(Object object)

使用微信内置地图查看位置

参数

Object object

属性 类型 默认值 必填 说明
latitude number   纬度,范围为-90~90,负数表示南纬。使用 gcj02 国测局坐标系
longitude number   经度,范围为-180~180,负数表示西经。使用 gcj02 国测局坐标系
scale number 18 缩放比例,范围5~18
name string   位置名
address string   地址的详细说明
success function   接口调用成功的回调函数
fail function   接口调用失败的回调函数
complete function   接口调用结束的回调函数(调用成功、失败都会执行)

示例代码

wx.getLocation({
 type: 'gcj02', //返回可以用于wx.openLocation的经纬度
 success (res) {
   const latitude = res.latitude
   const longitude = res.longitude
   wx.openLocation({
     latitude,
     longitude,
     scale: 18
   })
 }
})

(2)获取当前的地理位置、速度

      当用户离开小程序后,此接口无法调用

wx.getLocation(Object object)

调用前需要 用户授权 scope.userLocation

获取当前的地理位置、速度。当用户离开小程序后,此接口无法调用。

参数

Object object

属性 类型 默认值 必填 说明 最低版本
type string wgs84 wgs84 返回 gps 坐标,gcj02 返回可用于 wx.openLocation 的坐标  
altitude string false 传入 true 会返回高度信息,由于获取高度需要较高精确度,会减慢接口返回速度 1.6.0
success function   接口调用成功的回调函数  
fail function   接口调用失败的回调函数  
complete function   接口调用结束的回调函数(调用成功、失败都会执行)  

object.success 回调函数

参数
Object res
属性 类型 说明 最低版本
latitude number 纬度,范围为 -90~90,负数表示南纬  
longitude number 经度,范围为 -180~180,负数表示西经  
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

示例代码

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

注意

  • 工具中定位模拟使用IP定位,可能会有一定误差。且工具目前仅支持 gcj02 坐标。
  • 使用第三方服务进行逆地址解析时,请确认第三方服务默认的坐标系,正确进行坐标转换。

人工按钮授权,获取位置信息代码:

<button bindtap="getLocation">获取</button>

  getLocation(){
    var _this = this;
    wx.openSetting({
      success(res) {
        if (res.authSetting['scope.userLocation']) {
          wx.getLocation({
            type: 'wgs84',//默认wgs84是全球定位系统获取的坐标,gcj02是国家测绘局给出的坐标
            success: (res) => {
              console.log('经度' + res.longitude + ',纬度' + res.latitude);
              _this.setData({
                latitude: res.latitude,
                longitude: res.longitude
              })
            }
          })
        }
      }
    })
  }

【拓展】箭头函数this指向

谈到this指向的时候箭头函数的this指向和普通函数不一样的,

=>this指向的是定义时this指向的对象,不会改变

function()声明函数时的this指向会指向使用时所在的对象

所以在上面案例中,如果用交通员函数,则不用在最值前重定义this为_this

(3)打开地图选择位置wx.chooseLocation(Object object)

wx.chooseLocation(Object object)

调用前需要 用户授权 scope.userLocation

打开地图选择位置。

参数

Object object

属性 类型 默认值 必填 说明
success function   接口调用成功的回调函数
fail function   接口调用失败的回调函数
complete function   接口调用结束的回调函数(调用成功、失败都会执行)

object.success 回调函数

参数
Object res
属性 类型 说明
name string 位置名称
address string 详细地址
latitude string 纬度,浮点数,范围为-90~90,负数表示南纬。使用 gcj02 国测局坐标系
longitude string 经度,浮点数,范围为-180~180,负数表示西经。使用 gcj02 国测局坐标系

.

猜你喜欢

转载自www.cnblogs.com/jianxian/p/11111705.html