[GIS] ol.control.MousePosition EPSG:4326 over 180/-180 longitude (OL4)

openlayers

i will use a OpenLayers example in EPSG:4326, but the value of longitude is not wrapping on 180/-180 longitude.

How can i fix it?
My first problem is, i can't pick the values of latitude and longitude in a value for a if calculation.

if (lon > 180) {  
lon = (((lon / 180) - Math.floor(lon / 180)) * 180);
}
if (lon < -180) {
lon = (((((lon * -1) / 180) - Math.floor((lon * -1) / 180)) * (180 * -1) + 180));
}

How do I extract the coordinates into a variable?
Or is there another solution?

The OpenLayers Example:
https://openlayers.org/en/latest/examples/mouse-position.html

The OL example in a JSFiddle:
https://jsfiddle.net/eqjjp4u8/

Best Answer

Try this as your ol.control.MousePosition:

var mousePositionControl = new ol.control.MousePosition({
    coordinateFormat: function(coordinate) {
        lon = coordinate[0];
        lat = coordinate[1];
        lon = lon % 360;
        if (lon > 180) {  
          lon = lon - 360;
        } else if (lon < -180) {
          lon = 360 + lon;
        }
        modifiedCoordinate = [lon, lat]
        return ol.coordinate.format(modifiedCoordinate, "{x}, {y}", 4);
    },
    projection: 'EPSG:4326',
    className: 'custom-mouse-position',
    target: document.getElementById('mouse-position'),
    undefinedHTML: '&nbsp;'
});

Check out your modified JSFiddle.

Update: Now using modifiedCoordinate to limit the number of digits!