1

I am using Leaflet and Leaflet.draw to create a map. When I draw a rectangle on the map (as a user), the following code writes out the LatLng bounds of the rectangle.

    // add the newly drawn items to a layer
    map.on('draw:created', function (e) {
        var type = e.layerType,
            layer = e.layer;

        // binds things upon creation
        if (type === 'rectangle') {
            var bounds = layer.getBounds();
            layer.bindPopup(bounds.getNorthWest().toString() + "NW" + bounds.getSouthEast().toString() + "SE");
        }

        drawnItems.addLayer(layer);
    });

I want to update this when the rectangle is edited by the user. I think that something like this should be updated using the 'draw:edited' event and '_popup.SetContent', but the LatLng in the does not update.

    // update LatLng when edited
    map.on('draw:edited', function (e) {
        var type = e.layerType,
            layer = e.layer;

        // update popup
        if (type === 'rectangle') {
            var bounds = layer.getBounds();
            layer._popup.SetContent(bounds.getNorthWest().toString() + "NW" + bounds.getSouthEast().toString() + "SE");
        }
    });

Adding that second code block also means that I can only edit the first rectangle ever created. So it's clearly not working, but I don't know why.

user2441511
  • 11,036
  • 3
  • 25
  • 50

1 Answers1

2

I figured it out. For the draw:edited event, I needed to use the eachLayer method to iterate through each layer in e.layers, and then instanceof to check the layer type. I also bound a new popup instead of editing the old popup.

Here's the code, which also has a line break in the popup to make it more readable:

    // update LatLng value
    map.on('draw:edited', function (e) {
        var layers = e.layers;

        layers.eachLayer(function (layer) {
            // do whatever you want to each layer, here update LatLng
            if (layer instanceof L.Rectangle) {
                var bounds = layer.getBounds();
                layer.bindPopup(bounds.getNorthWest().toString() +  " NW<br>" + bounds.getSouthEast().toString() + " SE");
            }
        });
    });

Thanks to this question about retrieving layer type on edit for pointing me in the right direction.

Community
  • 1
  • 1
user2441511
  • 11,036
  • 3
  • 25
  • 50