Google Maps API に依存せずに 2 つの GPS 座標の距離を計算する方法があるかどうか疑問に思っています。
私のアプリは float で座標を受け取るか、アドレスに対して逆 GEO を実行する必要があります。
Google Maps API に依存せずに 2 つの GPS 座標の距離を計算する方法があるかどうか疑問に思っています。
私のアプリは float で座標を受け取るか、アドレスに対して逆 GEO を実行する必要があります。
地球上の2つの座標間の距離は、通常、Haversineの式を使用して計算されます。この式は、地球の形状と半径を考慮に入れています。これは、距離をメートルで計算するために使用するコードです。
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
puts distance([46.3625, 15.114444],[46.055556, 14.508333])
# => 57794.35510874037
geokit ruby gemを使用できます。これらの計算は内部で行われますが、必要に応じて、Google やその他のサービスを介したアドレスの解決もサポートされています。
require 'geokit'
current_location = Geokit::LatLng.new(37.79363,-122.396116)
destination = "37.786217,-122.41619"
current_location.distance_to(destination)
# Returns distance in miles: 1.211200074136264
bearing_to
(0 ~ 360 度の浮動小数点数で表される方向) とmidpoint_to
(.latitude および .longitude メソッドを実行できるオブジェクトを返す) を見つけることもできます。
@Lunivoreの答えの少し短くて分離されたパラメータバージョン
RAD_PER_DEG = Math::PI / 180
RM = 6371000 # Earth radius in meters
def distance_between(lat1, lon1, lat2, lon2)
lat1_rad, lat2_rad = lat1 * RAD_PER_DEG, lat2 * RAD_PER_DEG
lon1_rad, lon2_rad = lon1 * RAD_PER_DEG, lon2 * RAD_PER_DEG
a = Math.sin((lat2_rad - lat1_rad) / 2) ** 2 + Math.cos(lat1_rad) * Math.cos(lat2_rad) * Math.sin((lon2_rad - lon1_rad) / 2) ** 2
c = 2 * Math::atan2(Math::sqrt(a), Math::sqrt(1 - a))
RM * c # Delta in meters
end
あらかじめパッケージ化されたソリューションはわかりませんが、かなり簡単な計算のようです: http ://www.movable-type.co.uk/scripts/latlong.html
次のようにloc gemを使用できます。
require 'loc'
loc1 = Loc::Location[49.1, 2]
loc2 = Loc::Location[50, 3]
loc1.distance_to(loc2)
=> 123364.76538823603 # km