微信小程序用腾讯地图计算距离

  1. 首先引入地图
var QQMapWX = require('../../libs/qqmap/qqmap-wx-jssdk1.2/qqmap-wx-jssdk');
var qqmapsdk;
qqmapsdk = new QQMapWX({
  key: '填申请的key'
});

从接口获得列表list后,往目的地数组push值

let destinations = [];

for (var i = 0; i < list.length; i++) {
  destinations.push({
    location: {
      lat: list[i].lat,
      lng: list[i].lng
    }
  })
}

然后使用地图接口来计算距离

let self = this;
qqmapsdk.calculateDistance({
    from: {
      latitude: userLocation.lat,
      longitude: userLocation.lng
    }, // 从当前用户的定位算
    to: destinations,
    success: (res) => {
      let elements = res.result.elements;
      let box = [];
      for (let x = 0; x < elements.length; x++) {
        let distance;
        if (elements[x].distance >= 1000) {
          distance = (elements[x].distance / 1000) + 'km';
        } else {
          distance = parseInt(elements[x].distance) + 'm';
        }
        box.push({
          id: list[x].id, 
          ... // 其他属性(略)
          distance: distance
        })
      };

      self.setData({
        list: box
      })

    },
    fail: function (failRes) {},
    complete: function (completeRes) {}
 })

你可能感兴趣的:(微信小程序腾讯地图距离计算)