Last Updated: July 25, 2019
·
10.95K
· nifoc

Buffered Polyline

At work, we needed a simple way to buffer a polyline in order to search for stuff along the route from A to B. I'll explain how we used Google's Map API and JSTS in order to achieve this easily.

The first thing we had to do, was to "transform" each element in the overview_path (which the DirectionsService returns) to GeoJSON, because that's what JSTS understands.

var overviewPath = response.routes[0].overview_path,
    overviewPathGeo = [];
for(var i = 0; i < overviewPath.length; i++) {
    overviewPathGeo.push(
        [overviewPath[i].lng(), overviewPath[i].lat()]
    );
}

The next step was getting overviewPathGeo into JSTS and letting it do the work of buffering the line.

var distance = 10/111.12, // Roughly 10km
    geoInput = {
        type: "LineString",
        coordinates: overviewPathGeo
    };
var geoReader = new jsts.io.GeoJSONReader(),
    geoWriter = new jsts.io.GeoJSONWriter();
var geometry = geoReader.read(geoInput).buffer(distance);
var polygon = geoWriter.write(geometry);

The polygon variable now contains a polygon that neatly fits around the overviewPath, with a distance (buffer size) of roughly 10km.

Since it is nested, you need to call polygon.coordinates[0] in order to get back the coordinates of the polygon (as GeoJSON).

You could then use the the coordinates to draw the generated polygon on the map (along with the route), in order to produce something like this:

Example polygon from Hamburg to Aachen

4 Responses
Add your response

Great ! thanks Daniel !

over 1 year ago ·

Thanks! a lot for the code example

Newbie (on JSTS) questions:
1. Why the buffer shows wider in a horizontal path, than in a vertical path?
2. What is the background calculation that supports the "var distance = 10/111.12, // Roughly 10km" assumption?

over 1 year ago ·

Hi fausto,
your answer for question 2 is
10/111.12 -- converting km to degree.
1 degree = 111.12 km (approx)

Thanks,
Barman

over 1 year ago ·

The degrees in vertical and horizontal direction are about 1.5 times different in the given area (center of Europe). This depends on latitude, in equator they are equal (lat=long), but in another extreme, near poles they will be very off as longitude in real pole will be 0 meters. Think a bit how longitudes and latitudes work really on globe. So this buffering "hack" with lat/long creates exactly this issue - with horizontal line buffer will be much wider than with vertical one, and with diagonal places you would get some average and you may not even notice it. So if you need better accuracy then you cannot use this suggested code/method.

over 1 year ago ·