OpenLayers – How to Get a Drawn Feature ID in OpenLayers?

openlayers

Using OpenLayers 4. I can get the list of drawn features by calling getFeatures(), but calling getId() on each feature returns "undefined".
Here is a screenshot from console with the list of drawn features.

enter image description here

As far as I see "c" is the "id" which is returned by getId() and is "undefined" for all drawn features by default. So do drawn features have some automatically generated unique ids? The "xp" value seems to be the one. how can I get it then?

Best Answer

You can get the variable content of a given feature, such as xp using

feature.xp

For instance, to label each feature using its xp value, modify the example with

var vectorLayer = new ol.layer.Vector({
  source: new ol.source.Vector({
    url: 'https://openlayers.org/en/v4.6.5/examples/data/geojson/countries.geojson',
    format: new ol.format.GeoJSON()
  }),
  style: function(feature) {
    style.getText().setText(feature.xp.toString());
    return style;
  }
});

However since it is an internal variable name, there is no guarantee that it remains the same between versions. Similarly, there is no guarantee that a given feature keeps the same ID all the time. It is therefore dangerous to rely on this information, and even if it works today, it will eventually blow up one day.

As identified in the two related/duplicate answers and in @ThomasG77 answer, in order to use a reliable ID, you would need to manually set the ID when loading the data.