How to calculate the distance between two GPS coordinates without using Google Maps API?

前端 未结 7 1134
小鲜肉
小鲜肉 2020-12-08 02:56

I\'m wondering if there\'s a way to calculate the distance of two GPS coordinates without relying on Google Maps API.

My app may receive the coordinates in float or

7条回答
  •  盖世英雄少女心
    2020-12-08 03:18

    Just a little shorter & separated parameter version of @Lunivore's answer

    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
    

提交回复
热议问题