[GIS] Leafletjs get latlng center position of polyline

circleleafletline

After drawing a polyline, I would like to draw a circle from the center of this line whose radius encompasses the entire line.

For polyline's that have more than 2 points I can crudely get the center point like this:

// Get middle latLng on polyline
var streetLatLngs = layer.getLatLngs();
var numPoints = streetLatLngs.length;
var middleIndex = Math.round(numPoints / 2);
var centerPoint = streetLatLngs[middleIndex];

var circle = L.circle(centerPoint, 100);
circle.addTo(map);

Which produces:

center point

However as you can see when there are only 2 points, I can't calculate the center latlng, and I can't guarantee that the middleIndex is actually the middle point.

Once I have that I can get the radius with:

Math.round(streetLatLngs[0].distanceTo(streetLatLngs[numPoints - 1]) / 2);

which correctly produces the circle raduis:

enter image description here

Best Answer

Calculate the bounding box of the line (using getBounds() in Leaflet), put a circle with the center at the center of the bounding box, and the radius chosen as half width or height of the bounding box, whichever is highest.

Related Question