且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django - 我如何找到两个地点之间的距离?

更新时间:2023-02-01 22:28:13

按照tcarobruce的建议,这里是我以上的评论作为答案:



Zip代码数据库项目具有美国邮政编码的纬度和经度的数据库,可以是SQL或CSV。他们还提供以下用于距离计算的代码(由我编辑的slighlty):

 从数学导入sin,cos,弧度,度,acos 

def calc_dist(lat_a,long_a,lat_b,long_b):
lat_a =弧度(lat_a)
lat_b =弧度(lat_b)
long_diff =弧度long_a - long_b)
distance =(sin(lat_a)* sin(lat_b)+
cos(lat_a)* cos(lat_b)* cos(long_diff))
返回度(acos ))* 69.09

请注意,结果以法定里程给出。



编辑:由于John Machin的更正。


I have some users registered in my Django app and I want to simply be able to figure out the distance, geographically, between two users based on their zip code and then sort a list based on that. I would imagine this functionality isn't built into Django. I was looking at some options and stumbled across geodjango which seems like it might be overkill for what my needs are.

Following tcarobruce's suggestion, here is my above comment as an answer:

The Zip Code Database Project has a database of the latitudes and longitudes of the US zip codes, either as SQL or as CSV. They also provide the following code for distance calculation (slighlty edited by me):

from math import sin, cos, radians, degrees, acos

def calc_dist(lat_a, long_a, lat_b, long_b):
    lat_a = radians(lat_a)
    lat_b = radians(lat_b)
    long_diff = radians(long_a - long_b)
    distance = (sin(lat_a) * sin(lat_b) +
                cos(lat_a) * cos(lat_b) * cos(long_diff))
    return degrees(acos(distance)) * 69.09

Note that the result is given in statute miles.

Edit: Corrections due to John Machin.