The best way to calculate closest distance with Google API and Django

I have a page with a list of people, and I would like the user to click a button to sort this list by closest. The list is of objects with the variables LON and LAT for longitude and latitude.

I have made a function that calculates the distance based on Google Distance Matrix API. Here is the function:

def calculateDistance(lat1, lon1, lat2, lon2):
    gmaps = googlemaps.Client(key=config('MATRIX_API'))

    matrix = gmaps.distance_matrix((lat1,lon1), (lat2,lon2), mode="driving")
    print(matrix['rows'][0]['elements'][0]['distance']['text'])

I would like to know what is the best way to calculate the distance for all people in the list and order it inside the view that renders the page without creating a very heavy workload on the server.

I thought of an idea, is to do this in the background (using Django Celery) and store the distances in the database so that the sorting happens by retreiving the distances from the DB instead of making API calls everytime the person refreshes the page, for example:

class Distances(models.Model):
    visitor = models.ForeignKey(Visitor..... # Visitor looking for people
    person = models.ForeignKey(Person.... # Person on the list
    dist = models.CharField(.......

And the function above, gets executed in the background every time a new person gets added to the database, or the person changes his lon/lat data.

What do you think? and do you have a better way? Thank you.

PS: Keep in mind that in this case, the table will be pretty huge, if we had 1000 visitors and 5000 people on the list, the table will have 5 million records)

Back to Top