LineUtil
Quick answer
L.LineUtil offers polyline geometry helpers for simplification, viewport clipping, point to segment distance and length weighted centers, all computed on pixel point arrays. Every routine expects L.Point instances in layer pixel space, never raw latitude and longitude pairs. Convert coordinates with latLngToLayerPoint before calling any of them.
L.LineUtil. simplify ( points , tolerance ) → Point[]
Key points
- simplify applies Douglas-Peucker with a pixel tolerance, so higher values drop more vertices.
- clipSegment returns false when the whole segment lies outside the bounds rectangle.
- polylineCenter walks cumulative length and needs a CRS object for projection.
Example
var latlngs = polyline.getLatLngs();
var pts = latlngs.map(function (latlng) {
return map.latLngToLayerPoint(latlng);
});
/* 容差 1.5 像素:缩放后肉眼几乎看不出差别 */
var thin = L.LineUtil.simplify(pts, 1.5);
var back = thin.map(function (p) {
return map.layerPointToLatLng(p);
});
console.log(pts.length, '→', thin.length);
polyline.setLatLngs(back);var size = map.getSize();
var box = new L.Bounds(L.point(0, 0), L.point(size.x, size.y));
var a = map.latLngToLayerPoint(latlngA);
var b = map.latLngToLayerPoint(latlngB);
var clipped = L.LineUtil.clipSegment(a, b, box, false, true);
if (clipped) {
drawLine(clipped[0], clipped[1]);
}
Notes
- Passing raw LatLng arrays silently treats degrees as pixels and yields meaningless results.
- Simplification is tied to current zoom, so storing results distorts the line at other levels.
English edition written for Atlaslog. Code is taken from the original Chinese page and runs unchanged.
Atlaslog (2026). LineUtil. https://www.jingweizhi.com/en/leaflet/api/line-util.html (accessed 2026-11-03).