Pro*_*rod 15 javascript openlayers openlayers-3
我使用以下代码将功能添加到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);
Run Code Online (Sandbox Code Playgroud)
标记按预期显示,但click事件永远不会触发.我究竟做错了什么?
我应该注意到,在地图级别已经存在与"click"关联的处理程序,即
map.on("click", function(e) {
// do something
}, marker);
Run Code Online (Sandbox Code Playgroud)
Sim*_*Zyx 46
第一:功能不会点击!有关事件功能的信息,请访问http://openlayers.org/en/master/apidoc/ol.Feature.html.
为了检查功能是否被点击,有.forEachFeatureAtPixel(pixel, callback)ol.Map 的功能.(http://openlayers.org/en/master/apidoc/ol.Map.html#forEachFeatureAtPixel)对像素的每个要素执行回调.回调传递了2个参数:功能和功能所在的图层.
好知道的是.getEventPixel(event)功能,如果你不跟的OpenLayers事件处理程序,但与视口处理工作.如果您使用openlayers eventhandler,则该事件具有属性.pixel.(http://openlayers.org/en/master/apidoc/ol.Map.html#getEventPixel)方法.getEventCoordinate(event)也.getCoordinateFromPixels(pixels)可能有用.
所以你要把它像这样添加到你的map.on("点击",......:
map.on("click", function(e) {
map.forEachFeatureAtPixel(e.pixel, function (feature, layer) {
//do something
})
});
Run Code Online (Sandbox Code Playgroud)
与jQuery相同:
$(map.getViewport()).on("click", function(e) {
map.forEachFeatureAtPixel(map.getEventPixel(e), function (feature, layer) {
//do something
});
});
Run Code Online (Sandbox Code Playgroud)
与纯JS相同:
map.getViewport().addEventListener("click", function(e) {
map.forEachFeatureAtPixel(map.getEventPixel(e), function (feature, layer) {
//do something
});
});
Run Code Online (Sandbox Code Playgroud)
您可能还需要检查这个例子中,有此功能的两个用途,先用的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
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
39334 次 |
| 最近记录: |