Openlayers 3:从多个特征获取数据

Openlayers 3: Getting data from multiple features

我从 docs 中获取示例并添加了另一个功能。单击时,要素数据将显示在弹出窗口中。 我添加了另一个具有不同数据的功能。如果我单击系列中的功能,它将显示我单击的第一个功能的数据。如果我单击一个功能,请单击其他地方,然后单击另一个功能:它按预期工作。

我创建了一个 jsfiddle showing this problem. (In my firefox the map will only show if I click on the 'shield' icon in the top-left corner of the address bar and select 'Disable Protection on This Page'. See this question)

似乎使用此示例代码未采用正确的特征:

// display popup on click
map.on('click', function(evt) {
  var feature = map.forEachFeatureAtPixel(evt.pixel,
      function(feature, layer) {
        return feature;
      });
  if (feature) {
    var geometry = feature.getGeometry();
    var coord = geometry.getCoordinates();
    popup.setPosition(coord);
    $(element).popover({
      'placement': 'top',
      'html': true,
      'content': feature.get('name')
    });
    $(element).popover('show');
  } else {
    $(element).popover('destroy');
  }
});

我的目标是直接一个一个地点击特征,得到正确的数据显示。

编辑: 似乎这不是 OpenLayers 的问题,而是弹出窗口的问题。当我插入时:

console.log(feature.get('name'));

它将得出正确的数据。

您添加了两个并排的点。彼此如此接近,以至于您无法在视觉上区分它们。 将您的功能声明更改为:

var iconFeature = new ol.Feature({
  geometry: new ol.geom.Point([0, 0]),
  name: 'Null Island',
  population: 4000,
  rainfall: 500
});

var iconFeature2 = new ol.Feature({
  geometry: new ol.geom.Point([100000, 100000]),//here is the change
  name: 'Null Null Island',
  population: 200,
  rainfall: 100
});

另请注意,地图的默认投影是 EPSG:3857。您要传递的坐标似乎在 4326 上。

您还声明了两次 iconStyle 这没有任何区别,只是为了正确性

更新

您的主要问题来自 bootsrap popover。要解决这个问题,您需要做一些肮脏的工作并动态更新每次点击的内容。用这段代码来实现

  $(element).data("bs.popover").options.content= feature.get('name');
  $(element).popover("show");

还有一个fiddlehere