如何检查某些区域内是否有Python坐标

时间:2017-03-09 03:47:49

标签: python location coordinates latitude-longitude area

假设我有两种坐标,第一种称为center_point,第二种称为test_point。我想通过应用test_point阈值来了解center_point坐标是否在radius坐标附近。如果我写它,它就像:

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说明。

3 个答案:

答案 0 :(得分:13)

来自@ 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 :(得分:3)

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

答案 2 :(得分:2)

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")