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

久未见 提交于 2019-11-27 08:34:19

问题


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 for comparison to see whether the point is within the bound, i get some points outside it as shown in the screenshot below:

Map Screenshot

The code currently using to check if the point is within the circle bound is below:

        echo '
        var mark = L.marker([' . $r->coordinates[0]->longitude . ',' . $r->coordinates[0]->latitude . ']);

        if(circle.getBounds().contains(mark.getLatLng())){
            mark.addTo(map);
            mark.bindPopup("'.$info.'");
        }
        ';

I am looping into an array to retrieve the latitude and longitude and from there, to see whether the coordinates fills into the bound, if so, it adds it to the map with their corresponding popup

Any solution regarding this particular issue?

Thanks for helping


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/28742112/unable-to-display-only-the-points-within-a-specific-range-circle-using-the-ge

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!