pb22 pb22 - 4 years ago 125
Javascript Question

Getting a feature id on select

I'm having trouble getting the id of a feature that I select from my map. Here is an example of how I'm adding a feature:

var mylayer = map.getLayer('mylayerid');
var layersrc = mylayer.getSource();

var feature = new ol.Feature(new ol.geom.Point([0, 0]));
feature.setId(54);

layersrc.addFeature(feature);


Here is the setup I have for selecting a feature:

var selectSingleClick = new ol.interaction.Select();
selectSingleClick.on('select', function(e) {
// tried many things with e but can't get id of selected feature
});
map.addInteraction(selectSingleClick);


Is there a proper way to capture the feature id? Thanks!

Answer Source

I found a way to collect the id, though it is a bit convoluted. I follow the pointermove event to continuously collect the position of the mouse. Then when the map is clicked the position of the mouse at that instant is captured and we now have the ability to loop through each feature at that pixel location.

map.on('singleclick', function(evt) {
    var pixel = map.getPixelFromCoordinate(evt.coordinate);
    map.forEachFeatureAtPixel(pixel, function(feature) {
        console.log(feature.getId()); // id of selected feature
    });
});

If you have more than one feature at that location you will get multiple features. Hopefully this helps anyone else who has this problem.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download