从绘图管理器覆盖数组中删除元素

Axe*_*xel 1 javascript arrays google-maps

我目前正在研究基于地图的服务。在那里,用户可以通过使用drawingManager 绘制矩形和多边形来选择地图上的项目。在创建这些形状后,我将它们推送到全局数组,以保持对它们的控制,如下所示:

      google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
      if (e.type != google.maps.drawing.OverlayType.MARKER) {
      // Switch back to non-drawing mode after drawing a shape.
      drawingManager.setDrawingMode(null);
      var newShape = e.overlay;
      all_overlays.push(newShape);
      newShape.type = e.type;
      newShape.id = all_overlays.length-1;
      all_overlays[newShape.id].id = all_overlays.length-1;
}
Run Code Online (Sandbox Code Playgroud)

用户可以选择删除单个形状。我实现了这样的删除:

function deleteSelectedShape() {
if (selectedShape) {
    all_overlays.splice(selectedShape.id,1);
    while(jQuery.inArray(selectedShape.id, selected_shapes) != -1)
        {
        var shape_index = jQuery.inArray(selectedShape.id, selected_shapes);
        selected_shapes.splice(shape_index,1);
        selected_buoys.splice(shape_index,1);
        }
    selectedShape.setMap(null);
    selectedShape = '';
    buildList();
    highlightSelectedBuoys();   
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不起作用。例如,如果我得到一个具有 4 个形状 (ids:0,1,2,3) 的数组并删除 id=0 的数组,则 all_overlays 数组不会改变它的大小,这会在下一步中搞砸整个事情。我的错误在哪里?

rnr*_*ies 5

忘记了newShape.id拼接后形状的索引会改变。

使用indexOf代替:

 all_overlays.splice(all_overlays.indexOf(selectedShape),1);
Run Code Online (Sandbox Code Playgroud)

indexOf() 方法返回可以在数组中找到给定元素的第一个索引,如果不存在,则返回 -1。indexOf 使用严格相等(与 === 或三重相等运算符使用的方法相同)将 searchElement 与 Array 的元素进行比较。请注意,如果您将 -1 作为参数传递,则 splice 不会执行任何操作。

完整示例:

google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
      if (e.type != google.maps.drawing.OverlayType.MARKER) {
         // Switch back to non-drawing mode after drawing a shape.
         drawingManager.setDrawingMode(null);
         var newShape = e.overlay;
         all_overlays.push(newShape);
         newShape.type = e.type;
      }
}

function deleteSelectedShape() {
    if (selectedShape) {
        // here is the difference
        all_overlays.splice(all_overlays.indexOf(selectedShape),1);
        // here maybe you need the same fix.
        selected_shapes.splice(selected_shapes.indexOf(selectedShape),1);
        selected_buoys.splice(selected_buoys.indexOf(selectedShape),1);
        // remove from map.
        selectedShape.setMap(null);
        selectedShape = ''; // maybe should be undefined.
        // do stuffs
        buildList();
        highlightSelectedBuoys();   
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:这不是完全跨浏览器,因为indexOf并非所有浏览器都原生支持。 但是你可以自己实现它。阅读这篇文章以支持旧浏览器。