Florian Thürkow
Florian Thürkow

Reputation: 87

openlayers get latest feature added on vectorlayer

I try to get the latest featureID (e.g. 'OpenLayers_Feature_Vector_86') directly after adding the feature to the vectorlayer.

I tried to add an eventlistener:

eventListeners: {
 "featuresadded": function(feature) {
   alert(feature.fid);
  }
}

The feature is added with the following code:

vectors.addFeatures(geojson_format.read(featurecollection));

Thanks in advance Florian

Upvotes: 1

Views: 2197

Answers (1)

kryger
kryger

Reputation: 13181

featuresadded (note the plural form) passes a whole array of features added (even if it's a single feature it's still wrapped in an array), in your example you're trying to access a fid property of an array of features, which returns undefined. You should either:

  1. Listen for the featureadded event (singular form):

    The event object passed to listeners will have a feature property with a reference to the added feature.

  2. Extract the relevant feature inside the featuresadded handler, i.e.:

featuresadded: function(features) {
  var lastFeature = features[features.length - 1];
  var lastFeatureId = lastFeature.id;
}

As a general tip: I'd recommend using console.log instead of alert for debugging, it shows all the properties of an object, enabling you to inspect it (in this case: see that the ID property is called id, not fid). Alert coerces the object to a string, often showing something unhelpful like [object Object]

Upvotes: 2

Related Questions