你如何计算两个城市之间的距离?
如果您需要考虑地球的曲率,那么大圆距离就是您正在寻找的。 The Wikipedia article可能在解释公式如何比我更好的方面做得更好,并且还有this aviation formulary page涵盖了更详细的内容。
这些公式只是拼图的第一部分,如果你需要让这个工作适用于任意城市,你需要一个位置数据库来获取纬度/经度。幸运的是,你可以从Geonames.org免费获得这个,虽然有商业数据库可用(请谷歌)。所以,一般来说,查看你想要的两个城市,得到纬度/长度的联合并将它们插入公式,如the Wikipedia Worked Example。
其他建议:
最后但并非最不重要的是,Joel不久前写了一篇关于这个问题的文章,所以在这里你去:New Feature: Job Search
最好使用查找表来获得两个城市之间的距离。
这是有道理的,因为*计算距离a的公式计算量很大。*城市之间的距离不太可能改变。
因此,除非您需要非常具体(例如来自卫星或某些地形算法或其他地形的地形映射),您应该只是将城市列表和它们之间的距离保存到表格中并根据需要进行查找。
最近我一直在做很多工作。我发现SQL2008的新功能确实让这很容易。我可以在亚秒级的时间内找到Xkm为100k记录表的所有点......不会太破旧。
我的测试中的大圆(球面假设)方法与vincenty公式(elipsoidal假设,这就是地球的假设)相比大约需要2.5英里。
真正的诀窍是获得lat和long ..因为我正在使用Google。
@Jared - 对您的代码示例的一个小修正。第一个代码示例的最后一行应为:
dist = sqrt(dx*dx + dy*dy);
我同意,一旦你掌握了信息,如果它不会改变,那就以某种方式存储它。 @Marko Tinto感谢T-SQL示例。对于那些无法访问SQL Server或更喜欢其他方法的人:如果您需要高精度,请查看Wikipedia's entry on the Vincenty algorithm以获取更多信息。我相信有一个js实现,它会(如果还没有)很容易移植到其他语言。此外,该页面的底部是geographicLib的链接,它声称比Vincenty算法准确1000倍(如果你有好的数据,那可能很重要)。
你为什么要用Vincenty方法?因为地球不是一个完美的球体,所以这样的方法可以输入更准确的长轴和短轴来模拟地球。
我使用distancy这么简单干净
这在SQL Server 2008中非常容易使用地理类型。
SELECT geography::Point(lat1, lon1, 4326).STDistance(geography::Point(lat2, lon2, 4326))
-- computes distance in meters using eliptical model, accurate to the mm
4326是WGS84 elipsoidal Earth模型的SRID
您可以使用A*算法找到这两个城市之间的最短路径,这样您就可以获得距离。
如果你在谈论真正的球形行星上的两个真实城市之间的最短距离,比如地球,你需要great circle distance。
如果你在飞机上工作,你想要Euclidean distance“像乌鸦飞”:
// Cities are points x0,y0 and x1,y1 in kilometers or miles or Smoots[1]
dx = x1 - x0;
dy = y1 - y0;
dist = sqrt(dx*dx + dy*y);
不需要三角学!只是Pythagorean theorem和正方形总是正的事实,所以你不需要dx = abs(x1 - x0)等来得到一个正数来传递给sqrt()。
请注意,您可以在一行中执行此操作,并且编译器可能会将其减少为上述代码:
dist = sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0));
你可以从google map api获得两个城市之间的距离。这是Python中的一个实现
#!/usr/bin/python
import requests
from sys import argv
def get_distance(origin,destination):
gmap='http://maps.googleapis.com/maps/api/distancematrix/json'
payload={"origins":origin,"destinations":destination,"sensor":'false' }
try:
a=requests.get(gmap,params=payload)
data = a.json()
origin = str(data['origin_addresses'][0])
destination= str(data['destination_addresses'][0])
distance = data['rows'][0]['elements'][0]['distance']['text']
return distance,origin,destination
except Exception,e:
print "The %s or %destination does not exists :(" %(origin,destination)
exit()
if __name__=="__main__":
if len(argv)<3:
print "sorry Check the format"
else:
origin=argv[1]
destination=argv[2]
distance,origin,destination=get_distance(origin,destination)
print "%s ---> %s : %s" %(origin,destination,distance)
示例链接:https://gist.github.com/sarathsp06/cf063e47bcc515b51c84
您可以找到城市的Lat / Lon,然后使用Lat / Lon坐标的距离估计算法。
如果你需要一个代码示例我认为我有一个我可以在家里挖掘,但像许多以前的答案一样,你需要一个long / lat db来进行计算