8.5.1 获取与查看位置

wx.getLocation(OBJECT)

获取当前的地理位置、速度。当用户离开小程序后,此接口无法调用;当用户点击“显示在聊天顶部”时,此接口可继续调用。

OBJECT参数说明(表8-39):

表8-39

参数 类型 必填 说明
type String 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于wx.openLocation的坐标
success Function 接口调用成功的回调函数,返回内容详见返回参数说明。
fail Function 接口调用失败的回调函数
complete Function 接口调用结束的回调函数(调用成功、失败都会执行)

success返回参数说明(表8-40):

表8-40

参数 说明
latitude 纬度,浮点数,范围为-90~90,负数表示南纬
longitude 经度,浮点数,范围为-180~180,负数表示西经
speed 速度,浮点数,单位m/s
accuracy 位置的精确度

示例代码:

wx.getLocation({
  type: 'wgs84',
  success: function(res) {
    console.log(res.latitude)
    console.log(res.longitude)
    console.log(res.speed)
    console.log(res.accuracy)
  }
})

模拟器运行结果为:

39.084158
117.200983
undefined       //这里undefined的原因是模拟器没有获取速度的传感器
undefined

wx.chooseLocation(OBJECT)

打开地图选择位置。

OBJECT参数说明(表8-41):

表8-41

参数 类型 必填 说明
success Function 接口调用成功的回调函数,返回内容详见返回参数说明。
cancel Function 用户取消时调用
fail Function 接口调用失败的回调函数
complete Function 接口调用结束的回调函数(调用成功、失败都会执行)

success返回参数说明(表8-42):

表8-42

参数 说明
name 位置名称
address 详细地址
latitude 纬度,浮点数,范围为-90~90,负数表示南纬
longitude 经度,浮点数,范围为-180~180,负数表示西经

示例代码:

wx.chooseLocation({
      success: function(res){
        console.log(res.latitude)
        console.log(res.longitude)
      },
      fail: function() {
        // fail
      },
      complete: function() {
        // complete
      }
    })

调用此API会打开地图,在选择地点后点击右上角的“发送”按钮,即可获取所选地点的经纬度,地址,名称的信息。

wx.openLocation(OBJECT)

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

OBEJCT参数说明(表8-43):

表8-43

参数 类型 必填 说明
latitude Float 纬度,范围为-90~90,负数表示南纬
longitude Float 经度,范围为-180~180,负数表示西经
scale INT 缩放比例,范围5~18,默认为18
name String 位置名
address String 地址的详细说明
success Function 接口调用成功的回调函数
fail Function 接口调用失败的回调函数
complete Function 接口调用结束的回调函数(调用成功、失败都会执行)

示例代码:

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

wx.getLocation与wx.chooseLocation接口需要用户授权(询问用户是否允许小程序获取当前位置),需要对用户拒绝授权的场景作出处理(拒绝后使用默认地点或弹出提示框要求用户开启授权后重试)。

results matching ""

    No results matching ""