Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

227
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda