我从 docs 中获取了示例并添加了另一个功能。单击后,功能数据将显示在弹出窗口中。 我添加了另一个具有不同数据的功能。如果我单击系列中的功能,它将显示我单击的第一个功能的数据。如果我单击一个功能,请单击其他位置,然后单击另一个功能:它按预期工作。
我创建了一个 jsfiddle显示这个问题。 (在我的 Firefox 中,仅当我单击地址栏左上角的“盾牌”图标并选择“禁用此页面上的保护”时, map 才会显示。请参阅 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 的问题,而是 popover 的问题。当我插入时:
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
});
另请注意, map 的默认投影为 EPSG:3857。您尝试传递的坐标似乎是 4326。
您还声明了 iconStyle
两次,这没有任何区别,只是为了正确性
更新
您的主要问题来自 bootsrap popover
。为了解决这个问题,您需要做一些肮脏的工作并动态更新每次点击的内容。使用这段代码来实现
$(element).data("bs.popover").options.content= feature.get('name');
$(element).popover("show");
和一把 fiddle here
关于javascript - 开放层 3 : Getting data from multiple features,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38008166/