如何在openlayers3中从矢量层获取点坐标

How can I get the point coordinates from a vector layer in openlayers3?

本文关键字:获取 坐标 openlayers3      更新时间:2023-09-26

我使用OpenLayer3创建了一个带有矢量层的贴图。我现在想做的是遍历向量层,获取坐标并将其存储在数组中。

我试过这样的东西:

var store = vectorLayer.getGeometry().getExtent();

但我收到一个未定义的函数警告。

我也试过这样做:

var source = layer.getSource();
var features = source.getFeatures();

但我也收到了未定义的函数警告:

 TypeError: Cannot read property 'getExtent' of undefined 

这是我代码的一部分:

var url="http://localhost:8080/geoserver/wfs?&service=wfs&version=1.1.0&request=GetFeature&typeNames=dSpatialAnalysis:categoriesdata";
var shops_layer=new ol.layer.Vector({
    title: 'Shops',
    source: new ol.source.Vector({
        url: '/cgi-bin/proxy.cgi?url='+ encodeURIComponent(url),
        format: new ol.format.WFS({
        })
    }),
    style: iconStyle
});

map = new ol.Map({
    target:'map',
    renderer:'canvas',
    view: view,
    layers: [newLayer, shops_layer],
});

它不会改变最终结果,但可以使用forEachFeature:完成

var source = shops_layer.getSource();
source.forEachFeature(function(feature){
  var coord = feature.getGeometry().getCoordinates();
  // ...
});

这就是我解决问题的方法:

    // First access the source of the vectore layer
    var source = shops_layer.getSource();
    // Get the features of the layer 
    var features = source.getFeatures();
    var feature;
   // iterate through the array
    for (var i = 0, ii = features.length; i < ii; ++i) {
        feature = features[i];
        // get the geometry for each feature point
        geometry = feature.getGeometry();
        // get the first coordinate
        geometry_coords = geometry.getFirstCoordinate()
        // assign them to two variables
        geometry_coord_x = console.log(geometry_coords[0]);
        geometry_coord_y = console.log(geometry_coords[1]);
    }