Js OpenLayers 'drawend':如何设置ID而不需要在绘制后自行删除

admin2026-01-09 15:25:00玩家论坛

我们在JavaScript和OpenLayers方面还很新,而且还有点困难。在addInteraction()函数中,我们允许用户绘制特征(使用多边形、圆圈等)。在我们当前的they应用程序中,用户可以轻松地绘制这些功能,并且可以绘制多个功能。

代码语言:javascript复制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);

}

}这个很好用。现在,我们要将id添加到新绘制的特性中:

代码语言:javascript复制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);

}

}然而,现在我们只能画一个特征。在此之后,每次尝试绘制新特性时,它都会自行删除。更不用说,我们不知道如何然后也检索ID返回。

uid()函数:

代码语言:javascript复制// creates unique id's

function uid(){

var id = 0;

return function() {

if (arguments[0] === 0) {

id = 0;

}

return id++;

}

}这是为什么,怎么能解决呢?

友情链接