Search code examples
javascriptalgorithmcoordinatesopenlayers

LatitudeLongitude to LongitudeLatitude string. Swap coordinates in string


OpenLayers accepts coordinates in format Longitude-Latitude, and I want user to enter in Latitude-Longitude format. User inputs coordinates as a string in input field.

It is easy to swap if we have point:

var coo = ‘50, 30’;
OpenLayers.LonLat(JSON.parse(‘[‘+coo+’]’)[1], JSON.parse(‘[‘+coo+’]’)[0]);

But in case of line format:

var coo = ‘50 30, 55 35’;

It becomes a pain. Maybe there is a ready solutions for that case? I need to convert string from x1 y1, x2 y2, ... to y1 x1, y2 x2, ...


Solution

  • You can split your coordinates string into an array, reverse your coordinate pairs (from lat-lon to lon-lat) and transform it again into an array:

    let cooLonLat = coo
        .replaceAll(', ', ',')
        .split(',')
        .map(pair => pair.split(' ').reverse().join(' '))
        .join()
        .replaceAll(',', ', ')
    

    Check fiddle: https://jsfiddle.net/Lfcb9pak/