如何从 ReactJS 中的 OpenLayers 地图获取坐标?

How to get the coordinates from the OpenLayers Map in ReactJS?

Open Layer Map 中的三个位置以三角形连接。我试图在 OpenLayers 和 React JS 的帮助下获取所有三个位置(纬度和经度)。但不幸的是,我能够获得可见视图的纬度和经度,而不是标记的图层。

当我使用下面的代码时,它没有获取预期的经度和纬度,而是生成了可见的经度和纬度地图。

var glbox = map.getView().calculateExtent(map.getSize()); 
var box = proj.transformExtent(glbox,'EPSG:3857','EPSG:4326'); 
console.log("Latitude and longitude :",box);

所以,我也尝试了以下选项,但没有得到预期的经度和纬度。

console.log("Long and Lat :",map.getFeaturesAtPixel());  //--> null
console.log("Long and Lat :",map.getLayers());  
console.log("Long and Lat :",map.getFeaturesAtPixel());  //--> null

如何获取图像中显示的所有三个位置的纬度和经度?

它永远不会按照您当前的方式工作。 我是什么意思?我的意思是通过 map.getFeaturesAtPixel 是一种可行的方法,但您没有阅读 API docs。您至少需要向函数提供像素(x,y 屏幕坐标)。

您可以使用以下方法获取像素

map.on('click', evt => {
  console.log(evt.pixel);
})

我做了一个简单的演示来说明。转到 http://openlayers.org/en/latest/examples/gpx.html 并将以下代码粘贴到浏览器调试器控制台中。单击点并观察控制台中的行为。

map.on('click', evt => {
  var features = map.getFeaturesAtPixel(evt.pixel);
  if (features) {
    // Get name (but it depends of your data attributes)
    console.log(features
      .filter(feature => feature.getGeometry().getType() == 'Point')
      .map(feature => feature.get('name')));
    // Get the features, filter to only get Point, then get geometry
    // and coordinates, change projection to lon lat
    console.log(features
      .filter(feature => feature.getGeometry().getType() == 'Point')
      .map(feature => `Longitude, latitude: ${ol.proj.toLonLat(feature.getGeometry().getCoordinates()).join(', ')}`));
  }
})

根据反馈进行编辑。

要从 LineString 中获取点,只需执行

var featuresLinestringPointsCoordinates = vector.getSource().getFeatures()
  .map(feature => {
    return feature
      .getGeometry()
      .clone()
      .transform('EPSG:3857','EPSG:4326')
     .getCoordinates();
});
console.log(featuresLinestringPointsCoordinates);
// More readable and we only get the first linestring
console.table(featuresLinestringPointsCoordinates[0])

绘制 LineString

后在 the official snap demo 上测试