I am trying to make a selection via drawing a rectangle (or any shape) with leaflet draw. The selected features should be highlighted. I saw that there are various functions within the leaflet source that could help (contains from Bounds class and _containsPoint from Poly) however I keep getting an error saying that layer does not have this function. I have tried putting the draw layer into a new variable by creating a new L.Polygon object and calling _containsPoint(), but this gives a similar error - saying that the function does not exist for that polygon.

var marker1 = L.marker([51.441767, 5.470247],{
    draggable: true
}).addTo(map);

var someLayerGroup = L.featureGroup();
marker1.addTo(someLayerGroup);

map.addControl(new L.Control.Draw({
    edit: {
    featureGroup: drawnItems,
        edit: false
    },
    draw: {
        marker: false,
        circlemarker: false,
        polyline: false,
        circle:  false,
        polygon: {
          allowIntersection: false,
          showArea: true
        }
    }
}));

map.on(L.Draw.Event.CREATED, function (event) {
    var layer2 = event.layer;
    var type = event.layerType;
    if(type==='rectangle'){
        //do rectangle specific actions
        someLayerGroup.eachLayer(function(layer){
            if(layer2.contains(layer)){
            //set style of the point
            layer.setStyle({fillColor: '#CCCC00'});
            }
        });
    }
    drawnItems.addLayer(layer2);
});

JsFiddle: http://jsfiddle.net/ve2huzxw/2109/

up vote 0 down vote accepted

There are two problems:

Instead you can use CircleMarkers and instantiate a L.LatLngBounds object with the corners of the drawn rectangle. Then check whether the point is contained in the bounds and change the point's marker style if yes.

var marker1 = L.circleMarker([51.441767, 5.470247],{
  draggable: true
}).addTo(map);

[...]

map.on(L.Draw.Event.CREATED, function (event) {
  var layer2 = event.layer;
  var corners = [layer2._latlngs[0],layer2._latlngs[2]]  //retrieve corner of rectangle
  var type = event.layerType;
  if(type==='rectangle'){
    //do rectangle specific actions
    someLayerGroup.eachLayer(function(layer){
    if(L.latLngBounds(corners).contains(layer._latlng)){ //call .contains on an L.LatLngBounds object
        //set style of the point
        layer.setStyle({fillColor: '#CCCC00'});          //.setStyle of L.CircleMarker
      }
    });
  }
  drawnItems.addLayer(layer2);
});

JSFiddle: http://jsfiddle.net/ve2huzxw/2116/

  • Thanks! This has been bugging me for days! – Mieke Zwart Nov 7 at 15:12

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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