Leaflet Draw “Cannot read property 'enable' of undefined” adding control to geoJSON layer

后端 未结 2 1002
南方客
南方客 2020-12-04 02:57

I am trying to use leaflet\'s edit function on polygons that I loaded from my database. When I click on leaflet\'s edit button I get the error
Cannot read property

2条回答
  •  攒了一身酷
    2020-12-04 03:22

    Unfortunately Leaflet.draw plugin does not handle nested Layer Groups (same for Feature Groups / GeoJSON Layer Groups).

    That is the meaning of the Leaflet.draw #398 issue you reference: they advise looping through the child layers of your Layer/Feature/GeoJSON Layer Group (e.g. with their eachLayer method). If the child layer is a non-group layer, then add it to your editable Feature Group. If it is another nested group, then loop through its own child layers again.

    See the code proposed in that post:

    https://gis.stackexchange.com/questions/203540/how-to-edit-an-existing-layer-using-leaflet

    var geoJsonGroup = L.geoJson(myGeoJSON);
    addNonGroupLayers(geoJsonGroup, drawnItems);
    
    // Would benefit from https://github.com/Leaflet/Leaflet/issues/4461
    function addNonGroupLayers(sourceLayer, targetGroup) {
      if (sourceLayer instanceof L.LayerGroup) {
        sourceLayer.eachLayer(function(layer) {
          addNonGroupLayers(layer, targetGroup);
        });
      } else {
        targetGroup.addLayer(sourceLayer);
      }
    }
    

    In your very case, you can also refactor your code with 2 other solutions:

    • Instead of building your layerGroup (which is actually a Leaflet GeoJSON Layer Group) first and then add it into your Hazards Feature Group, make the latter a GeoJSON Layer Group from the beginning, and addData for each of your single Features (item):
    var Hazards = L.geoJSON(null, yourOptions).addTo(map);
    
    for (i in polygons) {
      var item = {
        "type" : "Feature",
        // etc.
      };
      // toAdd.push(item);
      Hazards.addData(item); // Directly add the GeoJSON Feature object
    }
    
    • Instead of building a GeoJSON Feature Object (item) and parse it into a Leaflet GeoJSON Layer, you can directly build a Leaflet Polygon and add it into your Hazards Layer/Feature Group:
    for (i in polygons) {
      var coords = polygons[i]["coordinates"];
      var style = getStyle(polygons[i]["category"]);
      var popup = ""; // fill it as you wish
    
      // Directly build a Leaflet layer instead of an intermediary GeoJSON Feature
      var itemLayer = L.polygon(coords, style).bindPopup(popup);
      itemLayer.id = polygons[i]["ID"];
      itemLayer.addTo(Hazards);
    }
    
    function getStyle(category) {
      switch (category) {
        case 'Rabid_Beavers': return {color: "#663326"};
        case 'Fire':   return {color: "#ff0000"};
        case 'Flood':   return {color: "#0000ff"};
      }
    }
    

提交回复
热议问题