Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
55
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

updated at

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

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

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やらライブラリやら使えないときのご参考まで。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
55
Help us understand the problem. What are the problem?