1

I am using Leaflet map. I am trying to have a popup message which shows the coordinates on drawn polygon. However when I am trying to edit the drawn polygon using the edit layer the coordinates in the popup is not updating it will still read the initial drawing:

map.on(L.Draw.Event.CREATED, (e) => {
  var type = e.layerType,
    layer = e.layer;

  if (type === 'rectangle' || type === 'polygon') {
    var latlngs = layer.getLatLngs()[0];
    var coordinates = latlngs.map(coord => [coord.lng, coord.lat]);

    var popupContent = '<p>Coordinates:</p><pre>' + JSON.stringify(coordinates, null, 2) + '</pre>';
    var popup = layer.bindPopup(popupContent);
    console.log("Created Event - Initial Coordinates:", popupContent);

    layer.on('editable:vertex:drag', (e) => {
      var editedLayer = e.layer;
      var editedCoordinates = editedLayer.getLatLngs()[0].map(coord => [coord.lng, coord.lat]);
      var updatedPopupContent = '<p>Coordinates:</p><pre>' + JSON.stringify(editedCoordinates, null, 2) + '</pre>';
      popup.setContent(updatedPopupContent);
      console.log("Editable Vertex Drag Event - Updated Coordinates:", updatedPopupContent);
    });
  }

  editableLayers.addLayer(layer);
});

1 Answer 1

2

I'm not very familiar with Leaflet.draw plugin and so also not with the editable:vertex:drag event. Instead of it I used edit event and that worked.

Here is the code that worked:

map.on(L.Draw.Event.CREATED, (e) => {
  var type = e.layerType,
    layer = e.layer;

  if (type === 'rectangle' || type === 'polygon') {
    var latlngs = layer.getLatLngs()[0];
    var coordinates = latlngs.map(coord => [coord.lng, coord.lat]);

    var popupContent = '<p>Coordinates:</p><pre>' + JSON.stringify(coordinates, null, 2) + '</pre>';
    layer.bindPopup(popupContent);

    layer.on('edit', (e) => {
      var editedLayer = e.target;
      var editedCoordinates = editedLayer.getLatLngs()[0].map(coord => [coord.lng, coord.lat]);
      var updatedPopupContent = '<p>Coordinates:</p><pre>' + JSON.stringify(editedCoordinates, null, 2) + '</pre>';
      editedLayer.getPopup().setContent(updatedPopupContent);
    });
  }

  editableLayers.addLayer(layer);
});
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.