Coordinate Transformations with Proj4js
Proj4js is a JavaScript library for performing coordinate transformations. It works in both browsers and Node.js.
Installation
Shell
npm install proj4 Register a CRS Definition
JavaScript
import proj4 from 'proj4';
// Register the CRS
proj4.defs("EPSG:5255",
"+proj=tmerc +lat_0=0 +lon_0=33 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs +type=crs"
); Search for any EPSG code on the home page and copy the definition from the Proj4js tab.
Transform Coordinates
JavaScript
// Transform from WGS84 to EPSG:5255
const result = proj4("EPSG:4326", "EPSG:5255", [33.0, 39.0]);
console.log(result); // [500000.00, 4317352.47]
// Inverse transform
const wgs84 = proj4("EPSG:5255", "EPSG:4326", [500000, 4317352]);
console.log(wgs84); // [33.0, 38.99...] Usage with Leaflet
JavaScript
import proj4 from 'proj4';
import 'proj4leaflet';
proj4.defs("EPSG:5255",
"+proj=tmerc +lat_0=0 +lon_0=33 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs"
);
const crs = new L.Proj.CRS('EPSG:5255',
proj4.defs('EPSG:5255'), {
origin: [0, 0],
resolutions: [8192, 4096, 2048, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1]
}
);
const map = L.map('map', { crs: crs }); Usage with OpenLayers
JavaScript
import proj4 from 'proj4';
import { register } from 'ol/proj/proj4';
proj4.defs("EPSG:5255",
"+proj=tmerc +lat_0=0 +lon_0=33 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs"
);
register(proj4);
// You can now use "EPSG:5255" in OpenLayers Notes
- Proj4js only includes
EPSG:4326andEPSG:3857by default. - All other CRS must be registered with
proj4.defs(). - Coordinate order is
[longitude, latitude](x, y).