55
34

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

緯度経度から2地点間の距離 (km) を計算する JavaScript

Last updated at Posted at 2018-08-05

2地点の緯度経度を指定して距離を km で返す JavaScript 関数

参照 → https://qiita.com/naotarou/items/628952e68fef059c6b1a

const R = Math.PI / 180;

function distance(lat1, lng1, lat2, lng2) {
  lat1 *= R;
  lng1 *= R;
  lat2 *= R;
  lng2 *= R;
  return 6371 * Math.acos(Math.cos(lat1) * Math.cos(lat2) * Math.cos(lng2 - lng1) + Math.sin(lat1) * Math.sin(lat2));
}

地球を(回転楕円体でなく)直径 半径 6,371km の球体としたときの計算らしい。
Google Maps も同じ計算らしい。

試してみる:

distance(35.666863,139.74954,35.663729,139.744047); // => 0.6063721931946154
distance(43.064313,141.347255,35.663729,139.744047); // => 834.321307653742

https://gist.github.com/kawanet/15c5a260ca3b98bd080bb87cdae57230 にも置いておいた。


2021/05/26 更新 直径→半径でした💦 Math.PI / 180 の除算定数を1回に集約。

55
34
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
55
34

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?