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

地址逆编码

复制代码
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 });
  }
相关推荐
00后程序员张14 小时前
HTTPS单向认证、双向认证、抓包原理与反抓包策略详解
网络协议·http·ios·小程序·https·uni-app·iphone
梦梦代码精16 小时前
LikeShop按摩到家系统:2026年本地生活创业新风口,上门服务O2O源码私有化部署实战
大数据·docker·小程序·uni-app·生活·高并发·开源软件
leduo668899o17 小时前
商城小程序自由容器支持图片自适应详解:从入门到实战全攻略
小程序
这是个栗子18 小时前
【uni-app微信小程序问题解决】Uni-app 微信小程序组件不渲染
微信小程序·小程序·uni-app
倒流时光三十年19 小时前
第四章 WXSS 样式系统与布局
spring boot·微信小程序
万岳科技系统开发19 小时前
外卖跑腿配送开发搭建指南:从用户下单到配送完成全流程解析
大数据·前端·小程序
靠谱品牌推荐官19 小时前
【高性能工程】每秒万次物联网数据高频握手:如何设计一套抗丢包的工业级小程序后端微服务架构?
物联网·小程序·架构
靠谱品牌推荐官19 小时前
【高并发实战】如何基于缓存穿透治理机制设计一套高可用的小程序本地缓存中台架构?
缓存·小程序·架构
小羊Yveesss19 小时前
商家小程序外卖订单打印方案:云打印机对接、分单逻辑与模板配置实战
小程序·apache
爱学习 爱分享2 天前
微信小程序html 在 webview 会打开再缩放一下
微信小程序·小程序·html