计算 2 个城市之间的距离

发布于 2024-07-04 11:11:13 字数 1454 浏览 10 评论 0 原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

¢蛋碎的人ぎ生 2024-07-11 11:11:13

如果您需要一个代码示例,我想我有一个可以在家里挖掘的代码示例,但是像前面的许多答案一样,您需要一个长/纬度数据库来进行计算

if you need a code example I think I have one I could dig up at home, but like many of the previous answers, you need a long / lat db to do the calculation

許願樹丅啲祈禱 2024-07-11 11:11:13

最好使用查找表来获取两个城市之间的距离。

这是有道理的,因为
* 计算距离 a 的公式计算量相当大。
* 城市之间的距离不太可能改变。

因此,除非您的需求非常具体(例如来自卫星或某些地形算法或其他东西的地形图),否则您实际上应该将城市列表以及它们之间的距离保存到表格中并根据需要进行查找。

It is better to use a look-up table for obtaining the distance between two cities.

This makes sense because
* The Formula to calculate the distance ais quite computationally intensive..
* Distance between cities is unlikely to change.

So unless you needs are very specific (like terrain mapping from a satellite or some or topography algorithm or something else), you should really just save the list of cities and distances between them, into a table and look it up as needed.

[浮城] 2024-07-11 11:11:13

我同意,一旦你掌握了信息,如果它不会改变,就以某种方式存储它。 @Marko Tinto 感谢您提供 T-SQL 示例。 对于那些无法访问 SQL Server 或更喜欢其他方法的人:如果您需要高精度,请查看 维基百科有关 Vincenty 算法的条目了解更多信息。 我相信有一个 js 实现,它可以(如果还没有的话)轻松移植到其他语言。 另外,该页面底部有一个指向 geographicLib 的链接,据称该链接比 1000 倍准确。 Vincenty 算法(如果你有那么好的数据,它可能很重要)。

为什么要使用 Vincenty 方法之类的方法? 因为地球不是一个完美的球体,所以类似的方法允许输入更准确的长轴和短轴来对地球进行建模。

I agree that once you have the info, if it's not going to change, store it somehow. @Marko Tinto Thanks for the T-SQL sample. For those who don't have access to SQL Server or prefer another method: If you need high accuracy, check out Wikipedia's entry on the Vincenty algorithm for more info. I believe there is a js implementation, which would (if not already) be easily ported to other languages. Also, at the bottom of that page is a link to geographicLib, which purports to be 1000 time more accurate than the Vincenty algorithm (if you have data that good, it might matter).

Why would you use something like the Vincenty method? Because the earth is not a perfect sphere and methods like that allow for inputting a more accurate major and minor axis for modeling the earth.

冰火雁神 2024-07-11 11:11:13

我使用 距离
如此简单干净

i use distancy
so simple and clean

隔纱相望 2024-07-11 11:11:13

@Jared - 对您的代码示例进行小幅更正。 第一个代码示例的最后一行应为:

dist = sqrt(dx*dx + dy*dy);

@Jared - a minor correction to your code example. The last line of the first code example should read:

dist = sqrt(dx*dx + dy*dy);
尽揽少女心 2024-07-11 11:11:13

我最近在这方面做了很多工作。 我发现 SQL2008 的新功能确实使这一切变得简单。 我可以在亚秒级的时间内找到 100k 记录表的 Xkm 范围内的所有点...还不错。

我测试中的大圆(球形假设)方法与文森蒂公式(椭球体假设,即地球)相比相差约 2.5 英里。

真正的技巧是获取纬度和经度……为此我正在使用谷歌。

I've been doing a lot of work with this recently. I'm finding SQL2008's new features really make this easy. I can find all the points that are withing Xkm of a 100k record table in sub-second time...not too shabby.

The great circle (spherical assumption) method in my testing was about 2.5 miles off when compared to the vincenty formula (elipsoidal assumption, which is what the earth is).

The real trick is getting the lat and long..for that I'm using Google.

我ぃ本無心為│何有愛 2024-07-11 11:11:13

如果您需要考虑地球的曲率,那么您需要的是大圆距离。 维基百科文章可能比我更好地解释了公式的工作原理,并且还有此航空处方页面,其中包含更多详细信息。

这些公式只是难题的第一部分,如果您需要使其适用于任意城市,您将需要一个位置数据库来获取纬度/经度。 幸运的是,你可以从 Geonames.org 免费获得这个,尽管有商业数据库可用(询问谷歌)。 因此,一般来说,查找您想要的两个城市,获取纬度/经度坐标并将它们代入公式,如 维基百科工作示例

其他建议:

  • 对于完整的商业解决方案,
    使用的是 PC Miler
    许多货运公司
    计算运费。
  • 调用 Google 地图(或其他)API。 如果您每天需要执行许多请求,请考虑在服务器上缓存结果。
  • 另外,如果您认为需要对数据进行分组,那么考虑为城市、郊区、城镇等建立一个等价数据库非常重要。 但这变得非常复杂,您可能找不到针对您的问题的一刀切的解决方案。

最后但并非最不重要的一点是,Joel 不久前写了一篇关于这个问题的文章,所以在这里:新功能:职位搜索

If you need to take the curvature of the earth into account, the Great-Circle distance is what you're looking for. The Wikipedia article probably does a better job of explaining how the formula works than me, and there's also this aviation formulary page that covers that goes into more detail.

The formulas are only the first part of the puzzle though, if you need to make this work for arbitrary cities, you'll need a location database to get the lat/long from. Luckily you can get this for free from Geonames.org, although there are commercial db's available (ask google). So, in general, look up the two cities you want, get the lat/long co-orinates and plug them into the formula as in the Wikipedia Worked Example.

Other suggestions:

  • For a full commercial solution,
    there's PC Miler which is used
    by many trucking companies to
    calculate shipping rates.
  • Make calls to the Google Maps (or other) api. If you need to do many requests per day, consider caching the results on the server.
  • Also very important is to consider building an equivalence database for cities, suburbs, towns etc. if you think you'll ever need to group your data. This gets really complicated though, and you may not find a one-size-fits-all solution for your problem.

Last but not least, Joel wrote an article about this problem a while back, so here you go: New Feature: Job Search

回眸一遍 2024-07-11 11:11:13

您找到城市的纬度/经度,然后使用纬度/经度坐标的距离估计算法。

You find the Lat/Lon of the city, then use a distance estimation algorithm for Lat/Lon coordinates.

默嘫て 2024-07-11 11:11:13

使用 SQL Server 2008 中的地理类型很容易做到这一点。4326

SELECT geography::Point(lat1, lon1, 4326).STDistance(geography::Point(lat2, lon2, 4326))
-- computes distance in meters using eliptical model, accurate to the mm

是 WGS84 椭球地球模型的 SRID

This is very easy to do with geography type in 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 is SRID for WGS84 elipsoidal Earth model

ぶ宁プ宁ぶ 2024-07-11 11:11:13

您可以使用 A* 算法来查找这两个城市之间的最短路径这样你就有了距离。

You ca use the A* algorithm to find the shortest path between those two cities and this way you'll have the distance.

骄傲 2024-07-11 11:11:13

如果您谈论的是真正的球形行星(例如地球)上两个真实城市之间的最短距离,您需要 大圆距离

If you're talking about the shortest distance between two real cities on a real spherical planet, like Earth, you want the great circle distance.

時窥 2024-07-11 11:11:13

如果您在飞机上工作并且想要欧几里得距离“如乌鸦飞翔”:

// 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);

不需要三角函数! 只是 毕达哥拉斯定理 以及平方始终为正的事实,因此您不需要 dx = abs(x1 - x0) 等以获取传递给 sqrt() 的正数。

请注意,您可能可以在一行中完成此操作,编译器可能会将其减少为上面的等效代码:

dist = sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0));

[1] http://en.wikipedia.org/wiki/Smoot

If you are working in the plane and you want the Euclidean distance "as the crow flies":

// 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);

No trigonometry needed! Just the Pythagorean theorem and the fact that squares are always positive so you don't need dx = abs(x1 - x0), etc. to get a positive number to pass to sqrt().

Note that you could probably do this in one line and a compiler would probably reduce it the equivalent above code:

dist = sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0));

[1] http://en.wikipedia.org/wiki/Smoot

和影子一齐双人舞 2024-07-11 11:11:13

您可以从 google 地图 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< /a>

You can get the distance between two cities from google map api.
Here is an implementation of it in 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)

Example link: https://gist.github.com/sarathsp06/cf063e47bcc515b51c84

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文