2点間の緯度・経度の距離を求める

  • Updated: 2023.08.08
  • Published: 2023.08.06
  • 705views
  • JavaScript

概要

2点間の緯度・経度の距離を求めます。直線の距離なので、Googleマップなどの経路の距離ではないので注意が必要です。

参考文献


スクリプト

function calculateDistance(lat1, lng1, lat2, lng2) {
  const radius = 6371; // Earth's radius in km
  const dLat = this.toRadians(lat2 - lat1);
  const dLng = this.toRadians(lng2 - lng1);
  const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(this.toRadians(lat1)) * Math.cos(this.toRadians(lat2)) *
    Math.sin(dLng / 2) * Math.sin(dLng / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  const distance = radius * c;

  return distance.toFixed(2);
}

function toRadians(degree) {
  return degree * (Math.PI / 180);
}

出力

let dis = calculateDistance(34.94402904,135.7129318,35.0158848,135.7053952);
console.log(dis); // 8.02

コメントを投稿する

CAPTCHA


関連記事

人気の投稿

最新の投稿

タグ

月別アーカイブ

Contact

WEB制作の依頼など気軽にお問い合わせください。

お問い合わせ