Question

I'm trying to write a Python function that determines whether or not a couple of geo-points are within 5 meters of distance each other. I have a couple of coordinates like: 13.09073, -86.3560933 and 13.09237, -86.3576067. I tried using a Haversine function but I'm not sure I'm getting the right value.

This is the function so far:

from math import sin, cos, pow, atan2, sqrt


def haversine(pos1, pos2):
    lat1 = float(pos1['lat'])
    long1 = float(pos1['long'])
    lat2 = float(pos2['lat'])
    long2 = float(pos2['long'])
    d_lat = (lat2 - lat1)
    d_long = (long2 - long1)

    a = pow(
        sin(d_lat / 2), 2) + cos(lat1) * cos(lat2) * pow(sin(d_long / 2), 2)
    c = 2 * atan2(sqrt(a), sqrt(1 - a))
    km = 6367 * c
    print 'km %f' % km
    print 'mts %f' % (km * 1000)


print haversine(
    {'lat': 0.0, 'long': 0.0}, {'lat': 0.0, 'long': 0.0000007852992})

That weird number is supposed to be "5 meters" of distance. I remove a conversion feature of degree_to_rad since I think my format is already on radians.

Was it helpful?

Solution

You're not going to be able to check against "5 meters in coordinates", because the difference in lat/lon values for points 5m apart is going to vary based on position on the surface of the sphere.

You can try testing your output against values from an existing script. It would not be very usual for lats and lons to be stored in radians, I would definitely check that.

There doesn't seem to be anything amiss with the calculations, but you probably mean to:

return km

at the end of the haversine function, so that print haversine(...) actual does something meaningful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top