【微信小程序】地址逆编码,根据经纬度计算直线距离

地址逆编码

复制代码
getLatLngByAddress(address) {
    // 校验地址是否为空
    if (!address) {
      wx.showModal({
        title: '提示',
        content: '请输入有效的地址',
      })
      return;
    }

    // 高德地图地理编码接口配置
    const amapKey = '替换成你自己的Key!';
    const url = `https://restapi.amap.com/v3/geocode/geo?address=${encodeURIComponent(address)}&key=${amapKey}`;

    wx.showLoading({ title: '获取中...' });

    // 发起请求
    wx.request({
      url,
      method: 'GET',
      success: (res) => {
        wx.hideLoading();
        const { status, info, geocodes } = res.data;
        // 接口调用成功且返回有效地址解析结果
        if (status === '1' && geocodes && geocodes.length > 0) {
          const [locationInfo] = geocodes;
          const [longitude, latitude] = locationInfo.location.split(','); // 高德返回格式:经度,纬度
          this.calculateDistance(longitude, latitude);
        } else {
          app.toast(info || '未查询到该地址的经纬度');
        }
      },
      fail: (err) => {
        wx.hideLoading();
        this.setData({ errorMsg: '网络错误,请稍后重试' });
        console.error('请求失败:', err);
      }
    });
  },

根据经纬度计算直线距离

复制代码
// 核心:计算两个经纬度之间的距离(Haversine公式)
  calculateDistance(lon, lat) {
    const { longitude, latitude } = this.data;
    // 提取经纬度并转数字
    const lat1 = Number(lat);
    const lng1 = Number(lon);
    const lat2 = Number(latitude);
    const lng2 = Number(longitude);

    // 角度转弧度(Math.sin/cos需要弧度值)
    const radLat1 = Math.PI * lat1 / 180;
    const radLat2 = Math.PI * lat2 / 180;
    const radLng1 = Math.PI * lng1 / 180;
    const radLng2 = Math.PI * lng2 / 180;

    // 计算纬度差、经度差
    const deltaLat = radLat1 - radLat2;
    const deltaLng = radLng1 - radLng2;

    // Haversine公式核心计算
    let distance = 2 * Math.asin(
      Math.sqrt(
        Math.pow(Math.sin(deltaLat / 2), 2) +
        Math.cos(radLat1) * Math.cos(radLat2) *
        Math.pow(Math.sin(deltaLng / 2), 2)
      )
    );
    // 地球平均半径6371公里,计算最终距离(保留2位小数)
    distance = distance * 6371;
    distance = Math.round(distance * 100) / 100;
    console.log(12121, distance);
    this.setData({ distance });
  }
相关推荐
mon_star°3 小时前
消防安全培训小程序项目亮点与功能清单
小程序
自然 醒4 小时前
uni-app开发微信小程序,如何使用towxml去渲染md格式和html标签格式的内容?
微信小程序·uni-app·html
编程迪4 小时前
基于Java和Vue开发的在线问诊系统医疗咨询小程序APP
小程序
CHU7290355 小时前
知识触手可及:在线教学课堂APP的沉浸式学习体验
前端·学习·小程序
竟未曾年少轻狂5 小时前
微信小程序-组件开发
微信小程序·小程序
CHU7290356 小时前
在线教学课堂APP功能版块设计方案:重构学习场景的交互逻辑
java·学习·小程序·重构
焦糖玛奇朵婷6 小时前
盲盒小程序开发,盲盒小程序怎么做
java·大数据·服务器·前端·小程序
想七想八不如114086 小时前
【GitHub开源】一款极简跨平台 Todo 应用:微信小程序 + Windows 桌面挂件 + 实时同步
微信小程序·开源·github
笨笨狗吞噬者7 小时前
代理的妙用:uni-app 小程序是怎样用 `Proxy` 和 `wrapper` 抹平平台差异的
前端·微信小程序·uni-app
CHU7290351 天前
便捷约玩,沉浸推理:线上剧本杀APP功能版块设计详解
前端·小程序