How to allow only one feature/polygon to be edited at a time with Leaflet?

荒凉一梦 提交于 2019-12-04 14:20:17

问题


It's been days I'm trying to solve my problem.

I have a polygon layer from a GeoJSON. I want to edit my polygons with the click event. When I click on a polygon it becomes editable but what I want is that when I click on another polygon, the first polygon is no longer in editable mode.

OpenLayers but naturally does not Leaflet.

Here's an excerpt from my code:

var editableLayers = new L.FeatureGroup().addTo(map);
var polygon_json;
    $.ajax({
    type: "GET",
    dataType: "json",
    url: "get_json.php", 
    success: function (response) {
                        meaux_json = L.geoJson(response, {
                        onEachFeature: onEachFeature    
                        });
                      }
    });

//edit the targeted polygon
function onEachFeature (feature, layer) {
                    editableLayers.addLayer(layer);
                    layer.on('click', function(e){
                    e.target.editing.enable();
                    });
               }

One person was able to do it but I am having difficulty understanding how : https://github.com/dwilhelm89/Ethermap


回答1:


I think you are close. In your onEachFeature function you should store the feature that was clicked so you can enable/disable editing in the click handler.

var selectedFeature = null;
//edit the targeted polygon
function onEachFeature (feature, layer) {
     editableLayers.addLayer(layer);
     layer.on('click', function(e){
          if(selectedFeature)
               selectedFeature.editing.disable();
          selectedFeature = e.target;
          e.target.editing.enable();
     });
}



回答2:


layer.on('click', function(event){
  editableLayers.eachLayer(function(layer) {
    layer.editing.disable()
  })
  event.target.editing.enable();
});


来源:https://stackoverflow.com/questions/26932125/how-to-allow-only-one-feature-polygon-to-be-edited-at-a-time-with-leaflet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!