gpt4 book ai didi

javascript - 将事件处理程序添加到 OpenLayers 3 中的功能?

转载 作者:可可西里 更新时间:2023-11-01 01:26:55 24 4
gpt4 key购买 nike

我正在使用以下代码向 OpenLayers 3 (OL3) 中的矢量图层添加特征:

marker = new ol.Feature({
geometry: new ol.geom.Point([longitude, latitude]),
name: "Location Marker"
});
markerStyle = new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 1.0],
anchorXUnits: "fraction",
anchorYUnits: "fraction",
src: "Content/Images/OpenLayers/marker_trans.png"
}),
zIndex: 100000
});
marker.setStyle(markerStyle);
marker.on("click", function(e) {
// do something
}, marker);
map.getSource().addFeature(marker);

标记按预期显示,但点击事件从未触发。我做错了什么?

我应该注意到在 map 级别已经有一个与“点击”关联的处理程序,即

map.on("click", function(e) {
// do something
}, marker);

最佳答案

首先:功能不会触发点击!有关触发事件功能的信息,请查看 http://openlayers.org/en/master/apidoc/ol.Feature.html .

为了检查一个特征是否被点击,有 ol.Map 的 .forEachFeatureAtPixel(pixel, callback) 函数。 ( http://openlayers.org/en/master/apidoc/ol.Map.html#forEachFeatureAtPixel ) 回调在像素的每个特征上执行。回调会传递 2 个参数:特征和特征所在的层。

值得一提的是 .getEventPixel(event) 函数,如果您不使用 openlayers 事件处理程序,而是使用视口(viewport)上的处理程序。如果您使用 openlayers 事件处理程序,则事件具有属性 .pixel。 ( http://openlayers.org/en/master/apidoc/ol.Map.html#getEventPixel ).getEventCoordinate(event).getCoordinateFromPixels(pixels) 方法也可能有用。

所以你会像这样将它添加到你的 map.on("click", ... :

map.on("click", function(e) {
map.forEachFeatureAtPixel(e.pixel, function (feature, layer) {
//do something
})
});

与 jQuery 相同:

$(map.getViewport()).on("click", function(e) {
map.forEachFeatureAtPixel(map.getEventPixel(e), function (feature, layer) {
//do something
});
});

与纯 JS 相同:

map.getViewport().addEventListener("click", function(e) {
map.forEachFeatureAtPixel(map.getEventPixel(e), function (feature, layer) {
//do something
});
});

您可能还想检查这个示例,此函数有两种用途,第一种用于 openlayers 事件,第二种用于 jQuery 事件: http://openlayers.org/en/master/examples/icon.js

注意事项

也可以使用 ol.interaction.Select ( http://openlayers.org/en/master/apidoc/ol.interaction.Select.html?unstable=true ) 来做到这一点,但在这种情况下这有点过分了。它有一些不直观的警告,这是由 openlayers 在内部将所选功能移动到另一个所谓的非托管层引起的。

无论如何,这是通过向属于交互的集合添加一个监听器来实现的。可以使用 .getFeatures() 检索该集合。

interaction.getFeatures().on("add", function (e) { 
// do something. e.element is the feature which was added
});

关于javascript - 将事件处理程序添加到 OpenLayers 3 中的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26391195/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com