微信小程序之地图功能

649 阅读1分钟

微信小程序地图组件:

wxml代码片段:

<map id="map" longitude="113.324520" latitude="23.099994" scale="14" controls="{{controls}}" bindcontroltap="controltap" markers="{{markers}}" bindmarkertap="markertap" polyline="{{polyline}}" bindregionchange="regionchange" show-location style="width: 100%; height: 300px;"></map>

page.js代码

Page({
  data: {
    markers: [{
      iconPath: "/resources/others.png",
      id: 0,
      latitude: 23.099994,
      longitude: 113.324520,
      width: 50,
      height: 50
    }],
    polyline: [{
      points: [{
        longitude: 113.3245211,
        latitude: 23.10229
      }, {
        longitude: 113.324520,
        latitude: 23.21229
      }],
      color:"#FF0000DD",
      width: 2,
      dottedLine: true
    }],
    controls: [{
      id: 1,
      iconPath: '/resources/location.png',
      position: {
        left: 0,
        top: 300 - 50,
        width: 50,
        height: 50
      },
      clickable: true
    }]
  },
  regionchange(e) {
    console.log(e.type)
  },
  markertap(e) {
    console.log(e.markerId)
  },
  controltap(e) {
    console.log(e.controlId)
  }
})

在做地图相关功能开发时,通常会遇到一种业务场景,即:根据当前地图的中心点加载对应周边的数据。

 regionchange(e) {
    console.log(e)
    // 地图发生变化的时候,获取中间点,也就是用户选择的位置toFixed
    if (e.type == 'end') {
      console.log(e)
      var that = this;
      this.mapCtx = wx.createMapContext("map");
      this.mapCtx.getCenterLocation({
        type: 'gcj02',
        success: function(res) {
          console.log(res)
          that.setData({
            latitude: res.latitude,
            longitude: res.longitude,
          })
        }
      })
    }
  },

如果只是这样,在初始化进入页面时,会发生频繁加载请求的过程,这是因为地图初始化加载过程中会有一个放大和缩小过程即比例尺的适配过程,所以在此过程中会不断的调取regionchange的方法,所以在e.type的判断时通常加(e.causedBy == 'scale' || e.causedBy == 'drag'),这样避免页面不断请求接口的问题。

参考文章:developers.weixin.qq.com/miniprogram…