Question

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 want to get the nearest city in my database to user city.

For example, if I have these cities in the database: Los Angeles, San Francisco and New York City, and I'm accessing from other city like Miami, I should see NYC selected because it's the nearest geographically.

What's the best way to do this quick and performance aware?

Was it helpful?

Solution

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.

OTHER TIPS

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!)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top