Skip to content

Instantly share code, notes, and snippets.

@bolatuly
Created March 2, 2021 08:09
Show Gist options
  • Save bolatuly/30180e804523a78bfc8e33340a649cff to your computer and use it in GitHub Desktop.
Save bolatuly/30180e804523a78bfc8e33340a649cff to your computer and use it in GitHub Desktop.
transform epsg:4326 <=> epsg:3857
/**
* epsg:3857 <=> epsg:4326
* https://wiki.openstreetmap.org/wiki/Mercator
*/
const EARTH_RADIUS = 6378137; //equatorial radius in m
function degree_to_radian(a) {
return a / (180 / Math.PI);
}
function radian_to_degree(a) {
return a * (180 / Math.PI);
}
function transform_3857_to_4326(x, y) {
const lon = radian_to_degree(x / EARTH_RADIUS);
const lat = radian_to_degree(2 * Math.atan(Math.exp(y / EARTH_RADIUS)) - Math.PI / 2);
return { lon, lat };
}
function transform_4326_to_3857(lon, lat) {
const x = degree_to_radian(lon) * EARTH_RADIUS;
const y = Math.log(Math.tan(degree_to_radian(lat) / 2 + Math.PI / 4)) * EARTH_RADIUS;
return { x, y };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment