Best way to get to the nearest city? Python / Django

I have a website with a limited number of cities in the database, and you need to show the user the nearest city to its current location.

I can get the location using the MaxMind API, but I want to get the nearest city in my database to the user's city.

For example, if I have these cities in the database: Los Angeles , San Francisco and New York City , and I get access from another city, such as Miami , I should see the selected NYC, because it is the nearest geographically.

What is the best way to do this quickly and efficiently?

+4
source share
2 answers

You must save 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 is implemented in Javascript here . The MaxMind API should provide you with latitude and longitude.

+7
source

Keep this in mind that whenever you add a city to your database, the off-line part of the code is executed, which calculates the closest city for each city that you have. You can indicate that each city points to a different city as the nearest city with a foreign key.

Now that you have everything pre-calculated, whenever there is a live request with the name of the city, you simply get into the database with the name of the city, and you can get to the nearest city using the foreign key you specified. (city --- foreignkey ---> city)

Now it will be very fast, since you previously calculated the nearest city offline and can immediately return the result for each request in real time.

But how often do you plan to add a city? Probably not so often. Thus, stand-alone preliminary calculations will be rare, even if it takes a little time. But real-time queries respond very quickly. (Others have already recommended a formula for calculating distance, so I will skip this part!)

0
source

All Articles