Wednesday, 6 November 2019

OpenLayers 3: Access feature by ID


I want to create a map with openlayers, add feature points, let people move the points and retrieve the new coordinates later. I have searched the net for two days but all I found was an example where you get the new coordinates while the move is in progress capturing the data of the event. But I want to access the feature later (on another event).


Everything works fine beside accessing the feature object afterwards to retrieve the coordinates.


Here is my working code:


    









And now I would like to retrieve the coordinates of the object with this function:


function getFeaturecoordinates(featureID) {
console.log('Feature Moved To:' + vectorSource.getFeatureById(featureID).getGeometry().getCoordinates());
}

But obviously it does not work. I also tried a lot of other possibilities to access the feature, e.g.


vectorLayer.getSource().getFeatureById(featureID).getGeometry().getCoordinates());

But they all do not work.



What is the right way to access the feature by featureID?



Answer



Your way of getting features out of a source by ID is correct, but you way of setting the ID is not.


In OpenLayers 3, you set the ID of a feature with the setId method. Including id in the constructor is valid, but only adds the id as a feature property (not as the feature's identifier).


var iconFeature = new ol.Feature({
id: 'addressfeature',
geometry: new ol.geom.Point(ol.proj.transform([18.3261549, 50.2499405], 'EPSG:4326', 'EPSG:3857')),
popuptext: 'This would be my moveable feature ',
});
// this is what set's the ID:

iconFeature.setId('addressfeature');

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...