小程序开发API之位置openLocation、getLocation、chooseLocation

版权声明:欢迎转载,可Chat交流,写博不易请标明出处: https://blog.csdn.net/JackJia2015/article/details/86736697

使用下面API的前提是声明用途如下

App.json

 "permission": {
    "scope.userLocation": {
      "desc": "你的位置信息将用于小程序位置接口的效果展示"
    }
  }

效果展示


在这里插入图片描述

wx.openLocation(Object object)

使用微信内置地图查看位置
参数Object object在这里插入图片描述

wx.getLocation(Object object)

获取当前的地理位置、速度。当用户离开小程序后,此接口无法调用。
调用前需要 用户授权 scope.userLocation
参数Object object在这里插入图片描述

object.success 回调函数 参数 res在这里插入图片描述

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

wx.chooseLocation(Object object)

打开地图选择位置。调用前需要 用户授权 scope.userLocation
参数Object object在这里插入图片描述

object.success 回调函数参数res在这里插入图片描述

示例
效果展示


在这里插入图片描述

代码
index.wxml

<!--index.wxml-->
<!-- 获取当前的地理位置、速度
  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 
-->
<!-- 打开地图选择位置
  name  string  位置名称
  address   string  详细地址
  latitude  string  纬度,浮点数,范围为-90~90,负数表示南纬。使用 gcj02 国测局坐标系
  longitude   string  经度,浮点数,范围为-180~180,负数表示西经。使用 gcj02 国测局坐标系
 -->

<button type="primary" bindtap="btnClick1">使用微信内置地图查看位置</button>
<view>纬度:{{latitude}} 纬度:{{longitude}} 速度:{{speed}} 高度:{{accuracy}}</view>
<button type="primary" bindtap="btnClick2">获取当前的地理位置、速度</button>
<view>纬度:{{latitude2}} 纬度:{{longitude2}} 位置名称:{{name}} 详细地址:{{address}}</view>
<button type="primary" bindtap="btnClick3">打开地图选择位置</button>

index.wxss

/**index.wxss**/
button{
  margin: 20rpx;
  font-size: 30rpx;
}

index.js

//index.js
Page({
  data: {
    
  },
  //使用微信内置地图查看位置
  btnClick1:function(){
    wx.getLocation({
      type: 'gcj02', // 返回可以用于wx.openLocation的经纬度
      success(res) {
        const latitude = res.latitude
        const longitude = res.longitude
        wx.openLocation({
          latitude,
          longitude,
          scale: 18
        })
      }
    })
  },
  //获取当前的地理位置、速度。
  btnClick2: function () {
    var that = this
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        console.log(res)
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          speed: res.speed,
          accuracy: res.accuracy
        })
      }
    })

  },
  // 打开地图选择位置
  btnClick3: function () {
    var that = this
    wx.chooseLocation({
      success: function (res) {
        console.log(res)
        that.setData({
          latitude2: res.latitude,
          longitude2: res.longitude,
          name: res.name,
          address: res.address
        })
        
      },
      fail: function () {
        // fail
      },
      complete: function () {
        // complete
      }
    })
  },
  onLoad: function (options) {
    
  },
})





猜你喜欢

转载自blog.csdn.net/JackJia2015/article/details/86736697