...
大前端

js 通过坐标计算两个坐标之间的距离

Haversine 公式计算两点之间的大圆距离(地球曲面距离)

直接上代码了

以米为单位

function calculateDistance(lat1, lng1, lat2, lng2) {
  const R = 6371000; // 地球半径,单位为米
  const toRad = x => x * Math.PI / 180;

  const dLat = toRad(lat2 - lat1);
  const dLng = toRad(lng2 - lng1);
  const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
            Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
            Math.sin(dLng / 2) * Math.sin(dLng / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  const distance = R * c;

  console.log('两点距离:', distance, '米');
  return distance;
}

以公里为单位

function calculateDistance(lat1, lng1, lat2, lng2) {
  const R = 6371; // 地球半径,单位:km
  const toRad = x => x * Math.PI / 180;

  const dLat = toRad(lat2 - lat1);
  const dLng = toRad(lng2 - lng1);
  const a = Math.sin(dLat / 2) ** 2 +
            Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
            Math.sin(dLng / 2) ** 2;
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  const distance = R * c; // 单位:km

  console.log('两点距离:', distance.toFixed(2), '公里');
  return distance;
}

示例:用户与天安门的距离

const targetLat = 39.9087;
const targetLng = 116.3975;

function calculateToTiananmen(lat, lng) {
  const km = calculateDistance(lat, lng, targetLat, targetLng);
  alert(`您距离天安门还有 ${km.toFixed(2)} 公里`);
}

如需四舍五入或保留 1-2 位小数,使用 .toFixed(2)。

edge浏览器google浏览器显示由该组织管理由你的组织管理解决方法 分享一个微信朋友圈点赞秒赞软件,无需下载一秒几千赞
biu biu biu
Arduino基础函数,常用函数大全 局域网扫描软件ipscan分享 win10/11: Windows Audio无法启动 错误 0x80070005:拒绝访问 arduino esp8266 连接mqtt服务器 arduino esp8266配网后储存密码 EEPROM储存数据简单教程