Pavan Kumar
Pavan Kumar

Reputation: 115

Finding the center of a circle drawn using leaflet draw and also calculating the distance between 2 latlong

Am new to JS and the below queries may looks simple thing.

Query: I have drawn multiple circles on the map and i need to fetch all the markers details available with in the circle.

In order to achieve that am trying to fetch the center of circle in lat long and calculating the distance of all markers on the map from that center of circle. if (distance <= radius) concluding the marker is with in the circle.

  1. How center of the circle is determined.
  2. how distance is calculated between the center and the marker ?

Thanks in Advance..

Upvotes: 0

Views: 1770

Answers (1)

Julien V
Julien V

Reputation: 895

Let's assume you have something like that somewhere :

var editableLayers = new L.FeatureGroup();

and also that you added this options to your L.Control.Draw :

edit: {
    featureGroup: editableLayers, //REQUIRED!!
    remove: false
}

as the L.Draw documentation says.

Now you can search your circles :

var circleList = [];
editableLayers.eachLayer( function (l) {
    if (l instanceof L.Circle) {
        circleList.push(l);
    }
});

Same way to search for the markers :

var markerList = [];
editableLayers.eachLayer( function (l) {
    if (l instanceof L.Marker) {
        markerList.push(l);
    }
});

Now you want any marker which is inside any circle :

var markersInside = [];
var i;
for (i=0; i<markerList.length; i++) {
    var j;
    var m = markerList[i];
    var mposition = m.getLatLng();
    for (j=0; j<circleList; j++) {
        var c = circleList[j];
        var cposition = c.getLatLng();
        var cradius = c.getRadius();
        if (cposition.distanceTo(mposition) <= cradius) {
            markersInside.push(m);
            break;
        }
    }
}

Here is a fiddle which artificially declares the featureGroup.

Do not hesitate to read leaflet doc which contains pretty much everything i used and is very well written.

Upvotes: 2

Related Questions