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!)
un33k
source share