最初にcenter_point
と呼ばれ、次にtest_point
と呼ばれる2種類の座標があるとします。 radius
しきい値を適用して、test_point
座標がcenter_point
座標に近いかどうかを知りたい。私がそれを書くと、そのようになります:
center_point = [{'lat': -7.7940023, 'lng': 110.3656535}]
test_point = [{'lat': -7.79457, 'lng': 110.36563}]
radius = 5 # in kilometer
Pythonでtest_point
からの半径の内側または外側にcenter_point
があるかどうかを確認するにはどうすればよいですか? Pythonでこの種のタスクを実行するにはどうすればよいですか?
予想される結果は、test_point
座標からのradius
の内側または外側にcenter_point
と表示されます。
コメントの@ user1753919の推奨から、私はここで答えを得ました: Haversine Formula in Python(Bearing and Distance between two GPS points)
最終コード:
from math import radians, cos, sin, asin, sqrt
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
return c * r
center_point = [{'lat': -7.7940023, 'lng': 110.3656535}]
test_point = [{'lat': -7.79457, 'lng': 110.36563}]
lat1 = center_point[0]['lat']
lon1 = center_point[0]['lng']
lat2 = test_point[0]['lat']
lon2 = test_point[0]['lng']
radius = 1.00 # in kilometer
a = haversine(lon1, lat1, lon2, lat2)
print('Distance (km) : ', a)
if a <= radius:
print('Inside the area')
else:
print('Outside the area')
ありがとう
from math import sqrt
a = center_point[0]['lat'] - test_point[0]['lat']
b = center_point[0]['lng'] - test_point[0]['lng']
c = sqrt(a * a + b * b)
if (c < radius):
print("inside")
else:
print("outside")
GeoPy はそれを正常に処理できます:
from geopy import distance
center_point = [{'lat': -7.7940023, 'lng': 110.3656535}]
test_point = [{'lat': -7.79457, 'lng': 110.36563}]
radius = 5 # in kilometer
center_point_Tuple = Tuple(center_point[0].values()) # (-7.7940023, 110.3656535)
test_point_Tuple = Tuple(test_point[0].values()) # (-7.79457, 110.36563)
dis = distance.distance(center_point_Tuple, test_point_Tuple).km
print("Distance: {}".format(dis)) # Distance: 0.0628380925748918
if dis <= radius:
print("{} point is inside the {} km radius from {} coordinate".format(test_point_Tuple, radius, center_point_Tuple))
else:
print("{} point is outside the {} km radius from {} coordinate".format(test_point_Tuple, radius, center_point_Tuple))
または、大圏の距離を知る必要がある場合:
dis = distance.great_circle(center_point_Tuple, test_point_Tuple).km
print("Distance: {}".format(dis)) # Distance: 0.0631785164583489