0

I'm working in a Django App that stores lat and lng for users. I need to find nearby events for users based on their previously-defined radius. For both Users and Events, I store Latitude and Longitude in a MySQL database.

I found an example of a raw query that implements the Haversine Formula. There is also a haversine package for python. How do I use the haversine package in a regular Django query?

gariepy
  • 3,576
  • 6
  • 21
  • 34
Gocht
  • 9,924
  • 3
  • 42
  • 81

1 Answers1

0

I would go ahead and add this function to my 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

This page is also related.

Community
  • 1
  • 1
Sait
  • 19,045
  • 18
  • 72
  • 99