如何在不使用Google Maps API的情况下计算两个GPS坐标之间的距离? [英] How to calculate the distance between two GPS coordinates without using Google Maps API?
本文介绍了如何在不使用Google Maps API的情况下计算两个GPS坐标之间的距离?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有方法可以计算两个GPS坐标的距离,而不依赖Google Maps API。
I'm wondering if there's a way to calculate the distance of two GPS coordinates without relying on Google Maps API.
我的应用程序可能会接收float或我不得不在地址上反转GEO。
My app may receive the coordinates in float or I would have to do reverse GEO on the addresses.
推荐答案
地球上两个坐标之间的距离通常使用Haversine配方。该公式考虑了地球的形状和半径。这是我用来计算以米为单位的距离的代码。
Distance between two coordinates on earth is usually calculated using Haversine formula. This formula takes into consideration earth shape and radius. This is the code I use to calculate distance in meters.
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
这篇关于如何在不使用Google Maps API的情况下计算两个GPS坐标之间的距离?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文