How to check if coordinate inside certain area Python

ytomo picture ytomo · Mar 9, 2017 · Viewed 14.8k times · Source

Lets say I have 2 kind of coordinate, first called center_point and second called test_point. I want to know if test_point coordinate is inside near or not to center_point coordinate by applying radius threshold. If I write it, its like:

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

radius = 5 # in kilometer

How to check if the test_point inside or outside the radius from center_point in Python? how I perform this kind task in Python?

Result expected will say that test_point inside or outside the radius from center_point coordinate.

Answer

ytomo picture ytomo · Mar 9, 2017

from recommendation of @user1753919 in his/her comment, I got the answer here: Haversine Formula in Python (Bearing and Distance between two GPS points)

final code:

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

Thanks