LoginSignup
62
55

More than 5 years have passed since last update.

緯度経度より距離を(地球の丸さも考えて)求める。

Last updated at Posted at 2015-01-06

緯度経度から距離を求めるとき、地球の丸さを考慮に入れても地球を真球に近似して良ければ難しいことはありません。

from math import sin, cos, acos, radians
earth_rad = 6378.137

def latlng_to_xyz(lat, lng):
    rlat, rlng = radians(lat), radians(lng)
    coslat = cos(rlat)
    return coslat*cos(rlng), coslat*sin(rlng), sin(rlat)

def dist_on_sphere(pos0, pos1, radius=earth_rad):
    xyz0, xyz1 = latlng_to_xyz(*pos0), latlng_to_xyz(*pos1)
    return acos(sum(x * y for x, y in zip(xyz0, xyz1)))*radius

Osaka = 34.702113, 135.494807
Tokyo = 35.681541, 139.767103
London = 51.476853, 0.0

print(dist_on_sphere(Osaka, Tokyo)) # 403.63km
print(dist_on_sphere(London, Tokyo)) # 9571.22km

さらに精度よく計算したければ、回転楕円体とかで近似する必要があったり、acos関数は1近傍で誤差か大きいとか改良の余地はありますが、カジュアルな目的ならこれでそこそこ行けるかと。

とにかく、別に丸みを考慮してもそんな複雑じゃありませんよ、ということで。APIやらライブラリやら使えないときのご参考まで。

62
55
1

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
62
55