我正在从读入的 KML 文件创建矢量源。 该文件中包含以下 LineString:
<LineString> <coordinates>-106.048668,36.247039,0 -106.67948647721,40.716490413454,0</coordinates>
</LineString>
之后我从矢量源创建了一个图层。 我如何计算几何坐标以从文件 (106..) 获取坐标值?
当使用 getCoordinates() 从我得到的特征的几何图形时:
[-11805283.721064927, 4334667.01649344, 0, -11875506.112730931, 4970613.574512913, 0]
相反,我想从文件中获取原始坐标
使用 OpenLayers 包中的
toLonLat()
ol/proj
.
import {toLonLat} from 'ol/proj';
const wgsCoordinate = toLonLat(coordinate.x, coordinate.y);
你有一个 EPSG:3587 x/y 和高度坐标的平面数组。在使用
toLonLat()
. 之前,您必须先分解它
// [x1, y2, z1, x2, y2, z2, ...] -> [[x1, y1, z1], [x2, y2, z2], ...]
const lonLat1 = toLonLat([x1, y1]);
const lonLatZ1 = [...lonLat1, z1];
运行完整示例的代码片段
// 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/[email protected]/dist/ol.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/ol.css">
<h2>WGS84 Coordinates Flat Array</h2>
<span id="flat-coordinates"></span>
<h2>WGS84 Coordinates</h2>
<span id="coordinates"></span>