在开发微信小程序时,如果要使用到查看自己与目的地的距离
1、使用微信小程序官方的API wx.getLocation来获取自己的位置
wx.getLocation({
type: 'gcj02',
success(res) {
const myLocation = { latitude: res.latitude, longitude: res.longitude }
that.setData({
myLocation: myLocation
})
2、使用腾讯位置服务的API把目的地地址转换成坐标
let that = this
qqmapsdk.geocoder({
//获取表单传入地址
address: i.address, //地址参数,例:固定地址,address: '北京市海淀区彩和坊路海淀西大街74号'
success: async function (res) {//成功后的回调
console.log(res);
var res = res.result;
i.a = { latitude: res.location.lat, longitude: res.location.lng }
that.getMyLocation()
},
})
3、使用腾讯位置服务的API计算自己与目的地的距离
const arr = this.data.newList
const myLocation = this.data.myLocation;
const promises = arr.map((item, index) => {
return new Promise((resolve, reject) => {
wx.request({
url: `https://apis.map.qq.com/ws/distance/v1/matrix?mode=walking`,
method: 'post',
data: {
"key": "你的密钥",
"from": `${myLocation.latitude},${myLocation.longitude}`,
"to": `${item.a.latitude},${item.a.longitude}`
},
success: function(res) {
const distance = Math.round((res.data.result.rows[0].elements[0].distance/1000) * 100) / 100;
resolve({ index, distance: distance }); // 解析 Promise 并返回索引和距离
},
fail: function(error) {
console.log(error);
reject(error); // 拒绝 Promise
}
});
});
});
// 使用 Promise.all 等待所有请求完成
Promise.all(promises)
.then(results => {
// 创建一个新数组,包含更新后的对象
const updatedArr = arr.map((item, index) => {
const result = results.find(r => r.index === index);
return result ? { ...item, distance: result.distance } : item;
});
// 使用新数组更新数据
this.setData({
newList: updatedArr
});
console.log(updatedArr); // 你可以在这里使用更新后的数组
})
.catch(error => {
console.error('An error occurred:', error);
// 这里可以添加额外的错误处理逻辑
});