PolyUtil
Quick answer
L.PolyUtil clips polygon rings to a pixel rectangle and computes area weighted or vertex averaged centers, mirroring the math Leaflet's renderers perform. Use it when writing custom canvas drawing or when a label needs a sensible anchor inside a polygon.
L.PolyUtil. clipPolygon ( points , bounds , round ?) → Point[]
Key points
- clipPolygon applies Sutherland-Hodgman clipping and expects an L.Bounds in pixel space.
- polygonCenter weights by projected area and requires a CRS argument.
- centroid averages vertices arithmetically and shifts toward dense vertex clusters.
Example
var size = map.getSize();
var box = new L.Bounds(L.point(0, 0), L.point(size.x, size.y));
var ring = polygon.getLatLngs()[0].map(function (latlng) {
return map.latLngToLayerPoint(latlng);
});
var clipped = L.PolyUtil.clipPolygon(ring, box, true);
ctx.beginPath();
clipped.forEach(function (p, i) {
if (i === 0) { ctx.moveTo(p.x, p.y); }
else { ctx.lineTo(p.x, p.y); }
});
ctx.closePath();
ctx.fill();var ring = polygon.getLatLngs()[0];
var center = L.PolyUtil.polygonCenter(ring, map.options.crs);
var average = L.PolyUtil.centroid(ring);
L.marker(center).bindTooltip('面积重心').addTo(map);
L.circleMarker(average, { radius: 4 }).bindTooltip('顶点平均').addTo(map);
Notes
- Both center functions accept a single ring only, so holes must be handled separately.
- Concave polygons can place the area centroid outside the shape itself.
English edition written for Atlaslog. Code is taken from the original Chinese page and runs unchanged.
Atlaslog (2026). PolyUtil. https://www.jingweizhi.com/en/leaflet/api/poly-util.html (accessed 2026-11-03).