# Leafletjs get latlng center position of polyline

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);
``````

Which produces:

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:

• By curiosity, what do you need this circle for? – julien Nov 26 '14 at 14:33
• I was going to attempt to darken the map and only have the map inside the circles as a lower opacity – Titan Nov 26 '14 at 14:35
• If this is just in the current view, then try using pixel locations to calculate decent radius they translate back to latlng. – Frank Phillips Nov 26 '14 at 15:44

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.