Back

Technologies:

javascriptjavascript
node.jsnode.js
avatar
Tolerim
a month ago

I encountered a TypeError while working with Leaflet.js, stating that marker.getLatLng is not a function.

In my project, I'm using OSM and leaflet with node backend to plot maps. To select a bounding box, I'm using the rectangle function of the leaflet draw plugin mentioned here: https://leaflet.github.io/Leaflet.draw/docs/leaflet-draw-latest.html. I have a script tag in my front-end file "leaflet2.html" which contains the following code snippet:

  const mymap = L.map("map");

  const drawnItems = new L.FeatureGroup();
  mymap.addLayer(drawnItems);

  const drawControl = new L.Control.Draw({
    edit: {
      featureGroup: drawnItems,
    },
    draw: {
      polyline: false,
      circle: false,
      circlemarker: false,
      marker: {
        icon: new L.Icon.Default(),
      },
    },
  });
  mymap.addControl(drawControl);


  async function getGeoJSONArr() {
    const response = await fetch("http://localhost:3000/data");
    const jsonArr = await response.json();
    console.log("jsonARR", jsonArr);
    const reversedCoords = jsonArr[0].slice().reverse();
    console.log(reversedCoords);
    return { jsonArr: jsonArr, reversedCoords: reversedCoords };
  }

  (async function buildMap(params) {
    const o = await getGeoJSONArr();
    console.log(o);
    const polyline1 = o.jsonArr;
    const reversedCoords = o.reversedCoords;
    L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
      attribution:
        'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors',
      maxZoom: 18,
    }).addTo(mymap);

    mymap.setView(reversedCoords, 13);


    // Add a polyline
    console.log("polyline1 ", polyline1);
    const reversedCoordinates = polyline1.map((coord) => coord.reverse());

    L.polyline(reversedCoordinates, { color: "blue" }).addTo(mymap);

 
  })();

  mymap.on(L.Draw.Event.CREATED, (event) => {
    const marker = event.layer;
    console.log('event layer ',marker);
    // const latlng = marker.getLatLng();
    // console.log(`Selected point: ${latlng.lat}, ${latlng.lng}`);
  });
Although I am able to select a rectangle, I get an error in the title and no bounding box in the console. How can I fix this issue?
Answers(2)
avatar
Vogi
a month ago
Verified Answer
The error you are seeing might be due to a bug in the Leaflet.draw plugin that prevents drawing of rectangles and circles on mobile (touch) devices if the map was created before Leaflet.draw was loaded. You can try creating the map after Leaflet.draw is loaded to see if that resolves the issue. If that doesn't work, you can try using the getLatLngs() method of Polyline to get an array of points in the path of your rectangle. You can then use this array to create a bounding box. If you still have issues, please provide more details about the error message you are seeing and any other relevant information so I can help you better.

Sources

Unable to draw Rectangle and Circle in Chrome w/Touch (under some ...Coordinates of Leaflet.Draw rectangle - Stack OverflowLeaflet.draw change polygon filling programmaticallyLeaflet Draw "Cannot read property 'enable' of undefined" adding ...L.Draw.Rectangle.initialize is not a function #708 - Github
avatar
Tolerim
a month ago
It looks like the issue is with the commented out code that is trying to get the latitude and longitude values from the selected rectangle. Since the rectangle is not a marker, it does not have a getLatLng() method which is causing the error. To get the bounding box of the selected rectangle, you can use the getBounds() method of the rectangle layer. Here's an example of how you can modify the code to get the bounding box:
mymap.on(L.Draw.Event.CREATED, (event) => {
  const layer = event.layer;
  const bounds = layer.getBounds();
  console.log('Bounding box:', bounds);
});
In this modified code, we are using the getBounds() method to get the rectangular bounds of the selected rectangle layer, and then logging them to the console. This should give you the desired output of the selected bounding box.
;