Ardahan Kisbet Ardahan Kisbet - 2 years ago 386
Javascript Question

How to get selected features properties dynamically in Open Layers 3?

I have two types in map which is Point and Polygon. Each type has own properties like id, doorNo, name etc. My feature list created by ;

var features = new ol.format.GeoJSON().readFeatures(geojsonObject, {
featureProjection: 'EPSG:3857'

If I call features by index I can get properties using get('property_name') function. For example;

features[0].getGeometry().getType() == "Point" // check this feature is Point or not
$doorNo = features[$index].get("doorNo");//this is also works

But at the same time I have a selectInteraction on my map. And when I select a feature I want to get all these same properties via button on click event. To do that I write this;

$('#btnSelected').on('click', function () {
if (selectInteraction) {
// use the features Collection to detect when a feature is selected,
// the collection will emit the add event
var selectedFeatures = selectInteraction.getFeatures();
console.log("Length: " + selectedFeatures.getLength());// this is works
console.log("Coordinates: " + selectedFeatures[0].getGeometry().getCoordinates());//THIS GAVES ME ERROR
console.log('there is no selected feature.');

So, in click event I want to write to console all feature property but even if selectedFeatures.length gaves me correct number I can't get any property at all.
Where am I going wrong?

enter image description here

Note: In the Map, blue one is selected point. And first two uncaught error is irrelevant for this question.

Answer Source

The getFeatures method returns an ol.Collection, not an Array.

ol.Collections do not support retrieving its items using the JS bracket notation. Instead of selectedFeatures[0] do selectedFeatures.item(0).

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