0

I have been working with leaflet-editable.js to allow the editing of shapes. Specifically I am creating a rectangle that will maintain an aspect ratio of 4:3 when a corner is dragged. I have created a function to calculate the aspect ratio and return the lat/lng of where the new corners should be drawn. I have attached this function to the event "editable:vertex:drag".

I'm not sure how to update the actual drawing of the rectangle to keep the scale. I have tried setting the object properties to the new bounds which updates but doesn't change the rectangle.

I think the answer is in refreshing the drawing of the rectangle but I don't know how to get the current rectangle instance nor how to refresh it.

Javascript is new for me

carto.on('editable:vertex:drag', function(e) {
  console.log(e);
  var cornersNe = e.vertex.latlngs[0], //ne
      cornersNw = e.vertex.latlngs[1], //nw
      cornersSw = e.vertex.latlngs[2], //sw
      cornersSe = e.vertex.latlngs[3]; //se
  var distanceWidth = carto.distance(cornersNw, cornersNe).toFixed(2);
  var distanceHeight = carto.distance(cornersSw, cornersNw).toFixed(2);
  var asR = aspectRatio(distanceWidth, distanceHeight, e.latlng.lat, e.latlng.lng);
  var index = e.vertex.getIndex(),
      next = e.vertex.getNext(),
      previous = e.vertex.getPrevious(),
      oppositeIndex = (index + 2) % 4,
      opposite = e.vertex.latlngs[oppositeIndex],
      bounds = new L.LatLngBounds(asR, opposite);
   // L.marker(bounds).addTo(carto);
  console.log('first set of bounds ', e.layer._bounds);
  console.log('bounds to set ', bounds);
  e.layer._bounds = bounds;
  console.log('Updated set ',e.layer._bounds);

I am open to other ways of doing it if this is too roundabout.

DoT
  • 3
  • 1

1 Answers1

0

Use the public function to set the bounds:

  e.layer.setBounds(bounds);
Falke Design
  • 10,635
  • 3
  • 15
  • 30
  • This looks promising however I'm not sure if it's because I'm using leaflet-editable.js but it throws an error: "latlngs[i].__vertex is undefined". I've looked in the source and found the code under the function "RefreshVertexMarkers" but not sure why it's occurring. I've tried passing the bounds in as an array and as objects and also as all 4 corners. – DoT May 04 '21 at 20:45
  • Can you please create a demo on jsfiddle? – Falke Design May 05 '21 at 04:45
  • I have created one for you here... https://jsfiddle.net/DanOT/g86t4hec/19/ I've also added a few notes but please excuse the mess, there is a fair few debugs and various things I've tried. – DoT May 05 '21 at 08:26
  • I will accept this answer as the right one, I managed to get the rectangle to set correctly when using the above but I had to comment out the "RefreshVertexMarkers" function in the leaflet-editable.js source code. Even though the rectangle is set, I now have a totally new problem of the vertex markers not being updated. – DoT May 16 '21 at 19:12