Search code examples
javascriptdrawingopenlayers

Js OpenLayers 'drawend': how to set ID without features removing itself after being drawn


We are fairly new with JavaScript and OpenLayers and are a bit struggling. In the addInteraction() function, we let the users draw features (using polygons, circles and etc.). In our current webapp, users can easily draw those features and they can draw multiple features.

let draw; // global so we can remove it later
function addInteraction() {

  const value = typeSelect.value;

  if (value !== 'None') {
    draw = new ol.interaction.Draw({
      source: source,
      type: typeSelect.value,
    }); 

map.addInteraction(draw);

  }
}

This works fine. Now, we want to add id's to the newly drawn features:

let draw; // global so we can remove it later
function addInteraction() {

  const value = typeSelect.value;

  if (value !== 'None') {
    draw = new ol.interaction.Draw({
      source: source,
      type: typeSelect.value,
    }); 

draw.on('drawend', function(event) {
  var id = uid(); // create a unique id // it is later needed to delete features
  event.feature.setId(id); // give the feature this id
});

map.addInteraction(draw);

  }
}

However, now we can only draw one feature. After that, every time you try to draw a new feature, it will remove itself. Let alone, we do not know how to then also retrieve the ID back.

The uid() function:

// creates unique id's
function uid(){
  var id = 0;
  return function() {
    if (arguments[0] === 0) {
      id = 0;
    }
    return id++;
  }
}

Why is this and how can this be fixed?


Solution

  • Your uid-Function returns another function, so you always set the ID of your feature to that function, therefore your features always get the same ID.

    You can easily confirm this by console logging the generated ID, it will show that it is a function, and not a number.

    To get the desired behaviour, you need to call the uid() function first to get the returned function, like this:

    var counterFunction = uid()
    draw.on('drawend', function(event) {
      var id = counterFunction();
      event.feature.setId(id);
    });
    

    retrieving IDs works via feature.getId().