Skip to content

Instantly share code, notes, and snippets.

@hugowetterberg
Created November 3, 2011 09:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hugowetterberg/1336132 to your computer and use it in GitHub Desktop.
Save hugowetterberg/1336132 to your computer and use it in GitHub Desktop.
Converts the distance between the WGS 84 coordinates pointA and pointB to meters.
###
Converts the distance between the WGS 84 coordinates pointA and pointB to meters.
Ported from http://groups.google.com/group/sci.geo.satellite-nav/msg/0bfca0bf8a986395
with the suggested radii-calculation optimization.
###
module.exports.WGS84DegreesToMeters = (pointA, pointB)->
radFactor = Math.PI/180
[lat1, lon1] = [pointA[0]*radFactor, pointA[1]*radFactor]
[lat2, lon2] = [pointB[0]*radFactor, pointB[1]*radFactor]
# Semi-major axis of WGS 84 ellipsoid, in meters.
a = 6378137.0
# Squared eccentricity of WGS 84 ellipsoid.
es = 6.694379990141320E-03
dlon = lon2 - lon1
dlat = lat2 - lat1
avg_lat = (lat2 + lat1) / 2
radii = Math.pow(Math.sin(avg_lat), 2)
# Radius of parallel.
rlon = a * Math.cos(avg_lat) / Math.sqrt(1 - es * radii)
# Radius of meridian.
rlat = a * (1 - es) / Math.pow(1 - es * radii, 1.5)
x = dlon * rlon
y = dlat * rlat
# The distance between the points, in meters.
Math.sqrt(x*x + y*y)
/*
Converts the distance between the WGS 84 coordinates pointA and pointB to meters.
Ported from http://groups.google.com/group/sci.geo.satellite-nav/msg/0bfca0bf8a986395
with the suggested optimization
*/
module.exports.WGS84DegreesToMeters = function(pointA, pointB) {
var a, avg_lat, dlat, dlon, es, lat1, lat2, lon1, lon2, radFactor, radii, rlat, rlon, x, y, _ref, _ref2;
radFactor = Math.PI / 180;
_ref = [pointA[0] * radFactor, pointA[1] * radFactor], lat1 = _ref[0], lon1 = _ref[1];
_ref2 = [pointB[0] * radFactor, pointB[1] * radFactor], lat2 = _ref2[0], lon2 = _ref2[1];
a = 6378137.0;
es = 6.694379990141320E-03;
dlon = lon2 - lon1;
dlat = lat2 - lat1;
avg_lat = (lat2 + lat1) / 2;
radii = Math.pow(Math.sin(avg_lat), 2);
rlon = a * Math.cos(avg_lat) / Math.sqrt(1 - es * radii);
rlat = a * (1 - es) / Math.pow(1 - es * radii, 1.5);
x = dlon * rlon;
y = dlat * rlat;
return Math.sqrt(x * x + y * y);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment