JavaScript Development Space

Convert EPSG-4326 to EPSG-3857 in JavaScript

To convert coordinates from EPSG:4326 (WGS84 - latitude/longitude) to EPSG:3857 (Web Mercator projection) in JavaScript, you can use the following formula. This converts latitude and longitude into X and Y coordinates suitable for map display (such as Google Maps or OpenStreetMap).

Formula for Conversion:

js
1 function convertCoordinates(lon, lat) {
2 const RADIUS = 6378137; // Earth radius in meters
3
4 // Convert longitude to X coordinate (meters)
5 const x = lon * (Math.PI / 180) * RADIUS;
6
7 // Convert latitude to Y coordinate (meters), with Mercator projection
8 const y = Math.log(Math.tan((Math.PI / 4) + (lat * Math.PI / 180) / 2)) * RADIUS;
9
10 return { x, y };
11 }
12
13 // Example usage:
14 const lon = -74.006; // Longitude (EPSG:4326)
15 const lat = 40.7128; // Latitude (EPSG:4326)
16
17 const result = convert4326To3857(lon, lat);
18 console.log(result); // { x: -8238310.235647004, y: 4970071.579142427 }

Explanation:

  • RADIUS is the Earth's radius in meters for the Web Mercator projection.

  • Longitude is converted to the X coordinate by multiplying the longitude (in degrees) by the radius and converting it to radians.

  • Latitude is converted to the Y coordinate using the Mercator projection formula, which involves logarithms and trigonometric functions.

This conversion is necessary for displaying geographic coordinates on web-based mapping systems that use the EPSG:3857 projection.

JavaScript Development Space

© 2024 JavaScript Development Space - Master JS and NodeJS. All rights reserved.