ruby中两个纬度/经度的距离

Distance on Two Lat / Lngs in Ruby

鉴于您有2000 lat / lng需要成对计算它们与另一个2000 lat / lng的距离的问题。即1比1。什么是最快的方法来完成ruby的处理。

C扩展会更快吗?或Java。目前,我正在使用GeoKit gem,在很多点上它有点慢。

编辑1:

此刻时间已超过30秒。


您如何使用GeoKit?在我的机器上,计算2000个点之间的距离需要0.016s。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
require 'benchmark'
require 'geokit'

ll_arr = 2000.times.map {|i|
              [Geokit::LatLng.new(rand(-180..180), rand(-180...180)),
               Geokit::LatLng.new(rand(-180..180), rand(-180...180))]}

distances = []

Benchmark.bm do |x|
  x.report do
    ll_arr.each do |ll|
      distances << ll[0].distance_from(ll[1], :units=>:kms)
    end
  end
end

10.times do |n|
  m = n * 200
  puts"ll #{m} from: #{ll_arr[m][0]} to: #{ll_arr[m][1]} distance: #{distances[m]}"
end

输出:

1
2
user     system      total        real
0.016000   0.000000   0.016000 (  0.015624)

结果似乎合理(以公里为单位):

1
2
3
4
5
6
7
8
9
10
ll 0 from: -180,71 to: 111,164 distance: 10136.21791028502
ll 200 from: 40,-127 to: -62,-23 distance: 14567.00843599676
ll 400 from: 23,-178 to: -163,-140 distance: 16014.598170496456
ll 600 from: 85,155 to: 25,3 distance: 7727.840511097989
ll 800 from: -26,57 to: 145,-36 distance: 11384.743155770688
ll 1000 from: -111,-137 to: 5,-5 distance: 9007.969496928148
ll 1200 from: 118,-98 to: -153,179 distance: 12295.886774709148
ll 1400 from: 44,-139 to: -91,-134 distance: 15024.485920445308
ll 1600 from: 48,126 to: -37,-92 distance: 16724.015574628884
ll 1800 from: -174,-77 to: -69,75 distance: 7306.820947156828


如果您使用PostgreSQL作为数据库,则可以查看http://postgis.refractions.net/

这将需要将纬度/经度点重新加载到具有PostGIS点数据类型的数据库表中,但是作为奖励,数据库现在应该能够处理诸如边界和边界之类的shapefile。

查找两个几何之间的距离的SQL函数

http://postgis.refractions.net/documentation/manual-1.5/ST_Distance.html

安装

http://postgis.refractions.net/documentation/manual-1.5/ch02.html

编辑:

如果这些仅存储在内存中,我想您可以使用类似spawn的东西(或滚动自己的版本)https://github.com/tra/spawn、https://github.com/rfc2822/spawn进行拆分计算分成几组。由于听起来距离计算只是在匹配对之间,因此将结果最后合并回去应该很简单(就像卡雷尔所建议的那样)。

您可以在结果完成时将结果流传输回客户端(如果不需要订购,尽管可以在收到最终结果时在客户端进行最终订购)。