Javascript 向 OpenLayers 3 中的功能添加事件处理程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26391195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:49:56  来源:igfitidea点击:

Adding event handler to feature in OpenLayers 3?

javascriptopenlayersopenlayers-3

提问by ProfNimrod

I am using the following code to add a feature to a vector layer in OpenLayers 3 (OL3):

我正在使用以下代码向 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);

The marker displays as expected, but the click event never fires. What am I doing wrong?

标记按预期显示,但单击事件永远不会触发。我究竟做错了什么?

I should note that there is already a handler associated with "click" at the map level, i.e.

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

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

回答by Simon Zyx

First: Features don't fire clicks! For information on the events features do fire, check http://openlayers.org/en/master/apidoc/ol.Feature.html.

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

For checking if a feature did get clicked, there is the .forEachFeatureAtPixel(pixel, callback)function of ol.Map. ( http://openlayers.org/en/master/apidoc/ol.Map.html#forEachFeatureAtPixel) The callback is executed on every feature at the pixel. The callback gets passed 2 arguments: the feature and the layer the feature is in.

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

Good to know is the .getEventPixel(event)function, if you don't work with openlayers event handlers but with handlers on the viewport. If your using openlayers eventhandler, the event has a property .pixel. (http://openlayers.org/en/master/apidoc/ol.Map.html#getEventPixel) The methods .getEventCoordinate(event)and .getCoordinateFromPixels(pixels)might be useful, too.

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

So you would add it like this to your map.on("click", ... :

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

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

Same thing with jQuery:

与 jQuery 相同:

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

Same thing with pure JS:

与纯 JS 相同:

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

You might also want to check this example, there are two uses of this function, first with openlayers events, the second with jQuery events: http://openlayers.org/en/master/examples/icon.js

您可能还想查看此示例,此功能有两种用途,第一种是 openlayers 事件,第二种是 jQuery 事件:http://openlayers.org/en/master/examples/icon.js

Note

笔记

There is also the possibility to do this with an ol.interaction.Select (http://openlayers.org/en/master/apidoc/ol.interaction.Select.html?unstable=true), but this is a little bit overpowered for this case. And it has some unintuitive caveats caused by openlayers internally moving the selected features to another so called unmanaged layer.

也可以使用 ol.interaction.Select ( http://openlayers.org/en/master/apidoc/ol.interaction.Select.html?unstable=true)来做到这一点,但这有点过分对于这种情况。并且它有一些不直观的警告,因为 openlayers 在内部将选定的特征移动到另一个所谓的非托管层。

Anyhow this works by adding a listener to the collection belonging to the interaction. The collection can be retrieved with .getFeatures().

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

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

回答by Costales

If you just want a click on a map, this will workfor you.

如果您只想点击地图,对您有用。

  var map = new ol.Map({
    target: 'map',
    layers: [
      new ol.layer.Tile({
        source: new ol.source.MapQuest({layer: 'sat'})
      })
    ],
    view: new ol.View({
      center: ol.proj.transform([37.41, 8.82], 'EPSG:4326', 'EPSG:3857'),
      zoom: 4
    })
  });

map.on("click", function(evt) {
    var coord = ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326');
    var lon = coord[0];
    var lat = coord[1];
    alert(lon);
    alert(lat);
});

回答by Amir Dashti

If you just need to add a marker on your map which is clickable, you can use overlays. In your HTML header define your marker's style:

如果您只需要在地图上添加一个可点击的标记,您可以使用叠加层。在您的 HTML 标头中定义标记的样式:

<style>
    #marker {
        width: 20px;
        height: 20px;
        border: 1px solid #088;
        border-radius: 10px;
        background-color: #0FF;
        opacity: 0.5;
    }
</style>

then in script part of your file, after the map is created:

然后在文件的脚本部分,在创建地图后:

    // add marker
    var pos = ol.proj.fromLonLat([0.01123, 0.00612]);
    var marker = new ol.Overlay({
        position: pos,
        positioning: 'center-center',
        element: $('<div id="marker" title="Marker"></div>')
            .popover({
                'placement': 'top',
                'html': true,
                'content': '<strong>anything...</strong>'
            })
            .on('click', function (e) { $(".location-popover").not(this).popover('hide'); }),
        stopEvent: false
    });
    map.addOverlay(marker);