Skip to content Skip to sidebar Skip to footer

Best Way To Get User Nearest City? Python/Django

I have a website with a limited number of cities in the database, and need to show the user the nearest city to his current location. I can get the location by MaxMind API, but I w

Solution 1:

You should store the approximate latitude and longitude for each city, calculate the latitude and longitude in degrees for the user, and then find the distance using the Haversine formula. It's implemented in Javascript here. The MaxMind API should give you the latitude and longitude.


Solution 2:

Have it such that whenever you add a city to your database, a piece of code is run (off-line) that calculates the closest city to every city that you have. You can have each city point to another city as its closest city with a foreignkey.

Now that you have everything pre-calculated, whenever there is a live request, with a name of a city, you just hit the database with the city name and you can get to the closest city by the foreignkey you have specified. (city ---foreignkey---> city )

Now that is going to be very fast as you have pre-calculated the closest city off-line and can return the result right away on each live request.

But how often do you plan to add a city? Probably not that often. So, the off-line pre-calculation would be rare even if it takes a bit of time to do. But live requests are responded to very fast. (others have already recommend the formula to use to calculate the distance, so I am going to skip that part!)


Post a Comment for "Best Way To Get User Nearest City? Python/Django"