微信小程序实现动态距离

在开发微信小程序时,如果要使用到查看自己与目的地的距离

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);  
        // 这里可以添加额外的错误处理逻辑  
      });

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值