Calculate distance between 2 GPS coordinates

前端 未结 29 3491
青春惊慌失措
青春惊慌失措 2020-11-21 23:34

How do I calculate distance between two GPS coordinates (using latitude and longitude)?

29条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 00:11

    This Lua code is adapted from stuff found on Wikipedia and in Robert Lipe's GPSbabel tool:

    local EARTH_RAD = 6378137.0 
      -- earth's radius in meters (official geoid datum, not 20,000km / pi)
    
    local radmiles = EARTH_RAD*100.0/2.54/12.0/5280.0;
      -- earth's radius in miles
    
    local multipliers = {
      radians = 1, miles = radmiles, mi = radmiles, feet = radmiles * 5280,
      meters = EARTH_RAD, m = EARTH_RAD, km = EARTH_RAD / 1000, 
      degrees = 360 / (2 * math.pi), min = 60 * 360 / (2 * math.pi)
    }
    
    function gcdist(pt1, pt2, units) -- return distance in radians or given units
      --- this formula works best for points close together or antipodal
      --- rounding error strikes when distance is one-quarter Earth's circumference
      --- (ref: wikipedia Great-circle distance)
      if not pt1.radians then pt1 = rad(pt1) end
      if not pt2.radians then pt2 = rad(pt2) end
      local sdlat = sin((pt1.lat - pt2.lat) / 2.0);
      local sdlon = sin((pt1.lon - pt2.lon) / 2.0);
      local res = sqrt(sdlat * sdlat + cos(pt1.lat) * cos(pt2.lat) * sdlon * sdlon);
      res = res > 1 and 1 or res < -1 and -1 or res
      res = 2 * asin(res);
      if units then return res * assert(multipliers[units])
      else return res
      end
    end
    

提交回复
热议问题