Best way to get user nearest city? Python/Django

試著忘記壹切 提交于 2019-12-03 00:45:29

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!