0

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.

chachan
  • 2,382
  • 1
  • 26
  • 41
  • 1
    If you aren't sure you are getting the right value, post examples or code. – Ramchandra Apte Nov 10 '13 at 16:14
  • possible duplicate of [How do I calculate distance between two latitude-longitude points?](http://stackoverflow.com/questions/27928/how-do-i-calculate-distance-between-two-latitude-longitude-points) – oefe Nov 10 '13 at 16:26
  • oefe, it could be. But I just want to know how much is 5 meters in coordinates, so I want apply conditions based on that value – chachan Nov 10 '13 at 16:29
  • What relation is between `13.09073, -86.3560933`, `13.09237, -86.3576067` and `0.0, 0.0` and `0.0, 0.0000007852992` points. What do you want to evaluate? – alko Nov 10 '13 at 16:47
  • No relation, those are samples that I was testing – chachan Nov 10 '13 at 16:50

1 Answers1

2

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.

ratatoskr
  • 427
  • 4
  • 7
  • Which format does Google Maps use for its links?. This is a testing link: https://www.google.com/maps/preview#!data=!1m4!1m3!1d1796!2d-84.0997365!3d9.9330108!2m1!1e3&fid=7. I can see -84.0997365 and 9.9330108. Are they on degrees? – chachan Nov 10 '13 at 18:19
  • Those are definitely degrees. – ratatoskr Nov 10 '13 at 18:55
  • Ok, I'll add the degree_to_rad conversion back to the function. Thank you! – chachan Nov 10 '13 at 19:02