8.5.2 地图组件控制

配合地图组件使用的API。

wx.createMapContext(mapId)

创建并返回map上下文mapContext对象。mapContext通过mapId跟一个地图组件绑定,通过它可以操作对应的地图组件。

mapContext对象的方法列表(表8-44):

表8-44

方法 参数 说明
getCenterLocation OBJECT 获取当前地图中心的经纬度,返回的是 gcj02 坐标系,可以用于 wx.openLocation
moveToLocation 将地图中心移动到当前定位点,需要配合map组件的show-location使用

getCenterLocation的OBJECT参数列表(表8-45):

表8-45

参数 类型 必填 说明
success Function 接口调用成功的回调函数 ,res = { longitude: "经度", latitude: "纬度"}
fail Function 接口调用失败的回调函数
complete Function 接口调用结束的回调函数(调用成功、失败都会执行)

示例代码:

<map id="myMap" show-location />

<button type="primary" bindtap="getCenterLocation">获取位置</button>
<button type="primary" bindtap="moveToLocation">移动位置</button>
onReady: function (e) {
    // 使用 wx.createMapContext 获取 map 上下文 
    this.mapCtx = wx.createMapContext('myMap')
  },
  getCenterLocation: function () {
    this.mapCtx.getCenterLocation({
      success: function (res) {
        console.log(res.longitude)
        console.log(res.latitude)
      }
    })
  },
  moveToLocation: function () {
    this.mapCtx.moveToLocation()
  },

运行结果为图8-5:

图8-5 地图组件控制API例图

results matching ""

    No results matching ""