2017-03-09 184 views
0

可以说我有2种坐标,第一个叫center_point,第二个叫test_point。我想知道如果test_point坐标是靠近或不是到center_point坐标应用radius阈值。如果我写它,它就像:如何检查某区域内的坐标Python

center_point = [{'lat': -7.7940023, 'lng': 110.3656535}] 
test_point = [{'lat': -7.79457, 'lng': 110.36563}] 

radius = 5 # in kilometer 

如何检查是否内部或从center_point在Python半径外的test_point?我如何在Python中执行这种类型的任务?

预计结果会说test_point内部或外部的radiuscenter_point之间的坐标。

+0

计算距离使用haversine公式HTTP: //stackoverflow.com/questions/4913349/haversine-formula-in-python-bearing-and-distance-between-two-gps-points并查看它是否小于r – plasmon360

+0

hi @ user1753919 tha它工作。 – ytomo

回答

6

在他/她的评论@ 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') 

感谢

1
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") 
+0

嗨,c'math.sqrt(aa + bb)'里面的'aa'和'bb'是指什么? – ytomo

+0

对不起,格式不正确。我编辑它更清楚。 – Egor