11

I'm new to OpenLayers 3 and I'm trying to add a property (id, name or label) to a feature to get it back on click later, to identify that particular feature.

Is it possible?

I haven't found any answer doing this yet. Something like:

var point_feature1 = new ol.Feature({ }); 
point_feature1.setProperties('description', "description 1");
point_feature1.setId(666);
...

And then onclick:

map.on('singleclick', function(evt) {             
  var feature = map.forEachFeatureAtPixel(evt.pixel,
    function(feature, layer) {
      console.log("feature",feature.getId());
      return [feature, layer];   
    });                                                           
});
nmtoken
  • 13,355
  • 5
  • 38
  • 87
Ademus
  • 119
  • 1
  • 1
  • 3

1 Answers1

20

You have an error in how you use the setProperties method. It is intended to set multiple properties at once and takes an object as input, which contains a list of key-value pairs:

point_feature1.setProperties({'name':'abcd', 'description':'xyz'})

The set method is used set one property at a time:

point_feature1.set('name', 'abcd')

With either method, you can then retrieve the name/description with the get method:

point_feature1.get('name');

The way you're using setId and getId looks fine.

rbkb
  • 656
  • 5
  • 8