2

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

  • 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
2

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.

  • Ah how did I miss the getCenter() function of LatLngBounds. Thank you! – Titan Nov 27 '14 at 8:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.