Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

229
Views
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?

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

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().

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!