Skip to content

Instantly share code, notes, and snippets.

@onderaltintas
Forked from springmeyer/degress2meters.js
Last active April 12, 2022 01:38
Show Gist options
  • Save onderaltintas/6649521 to your computer and use it in GitHub Desktop.
Save onderaltintas/6649521 to your computer and use it in GitHub Desktop.
javascript coordinate conversions between 900913(3857) - 4326(lat lon)
var degrees2meters = function(lon,lat) {
var x = lon * 20037508.34 / 180;
var y = Math.log(Math.tan((90 + lat) * Math.PI / 360)) / (Math.PI / 180);
y = y * 20037508.34 / 180;
return [x, y]
}
//test
lon= -77.035974
lat = 38.898717
console.log(degrees2meters(lon,lat))
// should result in: -8575605.398444, 4707174.018280
var meters2degress = function(x,y) {
var lon = x * 180 / 20037508.34 ;
//thanks magichim @ github for the correction
var lat = Math.atan(Math.exp(y * Math.PI / 20037508.34)) * 360 / Math.PI - 90;
return [lon, lat]
}
//test
x= -8575605.398444
y = 4707174.018280
console.log(meters2degress(x,y))
//should result in: -77.035974, 38.898717
@onderaltintas
Copy link
Author

you saved my life, thank you

I'm glad that I could help. But don't forget that it is just to translate 4326 to 900913(3857) and visa versa. This calculation cannot be used for length measurements because of high error margin.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment