我有一个hash(city: [coordinates])
这样的:
cities = {
l1: [41.91372380139719,-87.72308349609375],
l2: [42.092312110873536,-87.79449462890625],
l3: [42.08008203350686,-87.73406982421875],
l4: [41.86976539904969,-87.68325805664062],
l5: [41.8861255478388,-87.63381958007812],
l6: [41.8891926094646,-87.60635375976562],
l7: [41.91678953772886,-87.63107299804688],
l8: [41.92496411465408,-87.68051147460938],
l9: [41.87283324596932,-87.61734008789062],
l10: [41.84828634806966,-87.61184692382812],
l11: [41.86772008597142,-87.63931274414062],
l12: [41.88510316124205,-87.60498046875],
l13: [41.84930932360913,-87.62420654296875]
}
然后我计算第一个位置和其他位置之间的距离,如下所示,然后我将这些距离放入一个名为的数组中temp
:
temp = []
def distance loc1, loc2
rad_per_deg = Math::PI/180 # PI / 180
rkm = 6371 # Earth radius in kilometers
rm = rkm * 1000 # Radius in meters
dlat_rad = (loc2[0]-loc1[0]) * rad_per_deg # Delta, converted to rad
dlon_rad = (loc2[1]-loc1[1]) * rad_per_deg
lat1_rad, lon1_rad = loc1.map {|i| i * rad_per_deg }
lat2_rad, lon2_rad = loc2.map {|i| i * rad_per_deg }
a = Math.sin(dlat_rad/2)**2 + Math.cos(lat1_rad) * Math.cos(lat2_rad) * Math.sin(dlon_rad/2)**2
c = 2 * Math::atan2(Math::sqrt(a), Math::sqrt(1-a))
rm * c # Delta in meters
end
cityarr = cities.to_a
for i in 1..(cityarr.length-1) do
temp.push (distance [cityarr[0][1][0], cityarr[0][1][1]],[cityarr[i][1][0], cityarr[i][1][1]])
end
puts temp
这段代码有效,我得到了一个距离数组。我的最终目标是输出最接近第一个位置(“l1”)的位置。
例如:“L7 是离 L1 最近的位置”。由于临时数组中的元素与城市哈希中的键没有关联,我不知道该怎么做。我可以用它puts temp.min
来获得最小的距离,但这不会输出位置的名称。
有没有办法做到这一点?