乐趣区

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

  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) {}})
退出移动版