Search code examples
javascriptopenlayersmapbox-gl-js

How can I convert lng and lat from OpenLayers to mapbox?


OpenLayers uses an array like this: [15711464.77174924, 1340284.424706252] to handle center's coordinates, but for mapbox-gl I should set a value between -90 to 90 and I get this error:

Error: Invalid LngLat latitude value: must be between -90 and 90

So, is there any way to convert a coordinates like: 15711464.77174924 to between -90 to 90?


Solution

  • Spherical mercator coordinates assume the world is a sphere of radius 6378137 meters. To convert to degrees (based on the OpenLayers source code https://github.com/openlayers/openlayers/blob/main/src/ol/proj/epsg3857.js#L132-L134) the function would be

    function toLonLat(input) {
        const RADIUS = 6378137;
        const HALF_SIZE = Math.PI * RADIUS;
    
        const lon = (180 * input[0]) / HALF_SIZE;
        const lat =
          (360 * Math.atan(Math.exp(input[1] / RADIUS))) / Math.PI - 90;
    
        return [lon, lat];
    }