0

I was creating a Vector source from a KML file which I read in. The file had the following LineString in it:

<LineString>                                            <coordinates>-106.048668,36.247039,0 -106.67948647721,40.716490413454,0</coordinates>
</LineString>

After that I created a layer from the vector source. How can I calculate the coordinates from the geometry to get to the coordinates values from the file (106..)?

When using getCoordinates() from geometry of the feature I get:

[-11805283.721064927, 4334667.01649344, 0, -11875506.112730931, 4970613.574512913, 0]

Instead I wanted to get the original coordinates from the file

max0r
  • 1
  • 1

1 Answers1

0

Use toLonLat() from OpenLayers package ol/proj.

import {toLonLat} from 'ol/proj';
const wgsCoordinate = toLonLat(coordinate.x, coordinate.y);

You have a flat array of EPSG:3587 x/y and height coordinates. You would have to decompose that before using toLonLat().

// [x1, y2, z1, x2, y2, z2, ...] -> [[x1, y1, z1], [x2, y2, z2], ...]
const lonLat1 = toLonLat([x1, y1]);
const lonLatZ1 = [...lonLat1, z1];

Run the code snipped for the full example

// your original coordinates
const lineStringCoordiantesEPSG3857FlatArray = [-11805283.721064927, 4334667.01649344, 0, -11875506.112730931, 4970613.574512913, 0];

// extract single coordinates
const lineStringCoordinates = [];
for (let index = 0; index < lineStringCoordiantesEPSG3857FlatArray.length; index += 3) {
  // get the new coordinate
  lineStringCoordinates.push({
    x: lineStringCoordiantesEPSG3857FlatArray[index + 0],
    y: lineStringCoordiantesEPSG3857FlatArray[index + 1],
    z: lineStringCoordiantesEPSG3857FlatArray[index + 2]
  });
}

// add WGS84 coordinates -> Lon/Lat
const wgs84Coordinates = lineStringCoordinates.map(xyz => {
  // lon/lat
  const lonLat = ol.proj.toLonLat([xyz.x, xyz.y]);
  return [lonLat[0], lonLat[1], xyz.z];
});

let htmlOutput = document.getElementById('coordinates');
htmlOutput.innerHTML = JSON.stringify(wgs84Coordinates);

// all coordinates into one array
const wgs84CoordinatesFlatArray = wgs84Coordinates.reduce(function(arrayAccumulator, coordinate) {
  const concatenatedCoordinates = [...arrayAccumulator, ...coordinate];
  return concatenatedCoordinates;
}, []);

let htmlOutputFlatArray = document.getElementById('flat-coordinates');
htmlOutputFlatArray.innerHTML = JSON.stringify(wgs84CoordinatesFlatArray);
<script src="https://cdn.jsdelivr.net/npm/ol@v7.2.2/dist/ol.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@v7.2.2/ol.css">

<h2>WGS84 Coordinates Flat Array</h2>
<span id="flat-coordinates"></span>

<h2>WGS84 Coordinates</h2>
<span id="coordinates"></span>
Christoph
  • 386
  • 1
  • 4