Buffer a polyline by variable distance
04:30 30 Oct 2025

I have a list of points (x,y) that constitute a polyline, each point also has a value (m).

I want a polygon which is the buffer of the polyline with variable distance m. So at each point, the polygon is 2×m wide (if not overlapping), perpendicular to the direction of the polyline at that point.

A recipe is:

  • Divide up linestring into segments. For each segment:
    • buffer the 2 end points, each point with it's value
    • Take the convex hull of the buffers
  • Union all convex hulls.

I am looking for a solution that is computationally faster than implementing these steps naively using the corresponding shapely methods. I am looking for a solution that can be called from python.

All out of the box methods I have noted do not natively support variable distance, shapely's buffer or geopanda's buffer . These methods rely on the geos library, which has this feature noted in their issue tracker, but as of yet not actioned.

I have also noted an implementation in QGis, but I do not know I how I can port that to e.g. shapely object linestring.

Example

import numpy as np
from shapely import Point, convex_hull, MultiPoint, LineString, unary_union, Polygon


def segment_buffer(p1, p2, dist1, dist2):
    poly1 = Point(p1).buffer(dist1)
    poly2 = Point(p2).buffer(dist2)
    return convex_hull(MultiPoint(np.concatenate([poly1.exterior.coords, poly2.exterior.coords])))


def variable_buffer(polyline: LineString, distances):
    pts = list(polyline.coords)
    parts = []
    # for i in tqdm(range(1, len(pts)), desc='elements in polyline'):
    for i in range(1, len(pts)):
        dist0 = distances[i - 1]
        dist1 = distances[i]
        if dist0 > 0 or dist1 > 0:
            poly = segment_buffer(pts[i - 1], pts[i], dist0, dist1)
            parts.append(poly)

    buffer_geom = unary_union(parts)

    if buffer_geom.is_empty:
        return Polygon()
    return buffer_geom



def buffer(navigation, distances):
    navigation = np.asarray(navigation)
    if not navigation.size:
        return Polygon()
    if len(navigation) != len(distances):
        raise ValueError("Number of points does not match number of distances")
    geometry = LineString(navigation)
    return variable_buffer(geometry, distances)


from shapely import plotting, LineString

from main import buffer
import matplotlib.pyplot as plt


data = [[0,0],
        [5,-2],
        [10,2],
        [15,0],
        [20,5],
        [25,0],
        [35, 0],
        ]

buffer_distances = [3,4,0,2,5,2,2]

polygon = buffer(data, buffer_distances)

fig, ax = plt.subplots()
plotting.plot_polygon(polygon)
plotting.plot_line(LineString(data))
plt.show()
python gis