Unable to display only the points within a specific range (circle) using the .getBounds() function (Leaflet)

后端 未结 2 527
旧时难觅i
旧时难觅i 2020-12-11 23:01

I am trying to display a certain amount of points within a specific range, that is within a circle. But when using the .getBounds() function fo

相关标签:
2条回答
  • 2020-12-11 23:13

    You can create your own contains method and add it to the L.Circle class because it doesn't have one by default. You can use the utility method distanceTo of the L.LatLng objects to calculate distance between your marker and the circle's center and compare that to the circle's radius:

    L.Circle.include({
        contains: function (latLng) {
            return this.getLatLng().distanceTo(latLng) < this.getRadius();
        }
    });
    

    Now when you have a circle and a marker or latlng object you can do this:

    var map = L.map(...);
    
    var circle = L.circle(...).addTo(map),
        marker = L.marker(...).addTo(map);
        latLng = L.latLng(...);
    
    // Returns true when in the circle and false when outside
    circle.contains(marker.getLatLng());
    circle.contains(latLng);
    

    Working example on Plunker: http://plnkr.co/edit/OPF7DM?p=preview

    L.Circle reference: http://leafletjs.com/reference.html#circle

    L.Marker reference: http://leafletjs.com/reference.html#marker

    L.LatLng reference: http://leafletjs.com/reference.html#latlng

    0 讨论(0)
  • 2020-12-11 23:22

    The method getBounds() always returns a rectangular area. Hence it can't be used for checking whether a non-rectangular object contains a given point.

    For a circle you should be able to calculate the distance (distanceTo()) of the point to the circle's center (getLatLng()) and check whether it is smaller than the circle's radius (getRadius()). Note that the distance and radius are in meters.

    0 讨论(0)
提交回复
热议问题