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

地址逆编码

复制代码
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 });
  }
相关推荐
2501_915106321 小时前
app 上架过程,安装包准备、证书与描述文件管理、安装测试、上传
android·ios·小程序·https·uni-app·iphone·webview
2501_915106321 小时前
使用 Sniffmaster TCP 抓包和 Wireshark 网络分析
网络协议·tcp/ip·ios·小程序·uni-app·wireshark·iphone
宠友信息2 小时前
2025社交+IM及时通讯社区APP仿小红书小程序
java·spring boot·小程序·uni-app·web app
“负拾捌”3 小时前
python + uniapp 结合腾讯云实现实时语音识别功能(WebSocket)
python·websocket·微信小程序·uni-app·大模型·腾讯云·语音识别
换日线°21 小时前
NFC标签打开微信小程序
前端·微信小程序
光影少年1 天前
AIGC + Taro / 小程序
小程序·aigc·taro
2501_915918411 天前
在 iOS 环境下查看 App 详细信息与文件目录
android·ios·小程序·https·uni-app·iphone·webview
2501_916007471 天前
没有 Mac 用户如何上架 App Store,IPA生成、证书与描述文件管理、跨平台上传
android·macos·ios·小程序·uni-app·iphone·webview
天空属于哈夫克31 天前
Go 语言实战:构建一个企微外部群“技术贴收藏夹”小程序后端
小程序·golang·企业微信
菜鸟una1 天前
【微信小程序+Taro 3+NutUI 3】input (nut-input) 、 textarea (nut-texteare)类型使用避坑
前端·vue.js·微信小程序·小程序·taro