2

I have a LineString:

[
[
    -122.263923,
    37.87459
],
[
    -122.263942,
    37.874587
],
[
    -122.264151,
    37.874534
],
[
    -122.264231,
    37.874511
],
[
    -122.264285,
    37.874495
],
[
    -122.264356,
    37.874472
],
[
    -122.264441,
    37.874441
],
[
    -122.264589,
    37.874381
],
[
    -122.264681,
    37.874346
],
[
    -122.264747,
    37.874334
],
[
    -122.265209,
    37.874271
],
[
    -122.265329,
    37.874258
],
[
    -122.265382,
    37.874252
],
[
    -122.266071,
    37.874169
],
[
    -122.266145,
    37.87416
],
[
    -122.266291,
    37.87415
]]

And I want to add a new coordinate in that line [-122.263923, 37.87459]

I'm not sure how to find the right index. I can find the closest Point on the (Multi)LineString, but I'm not sure the new coordinate should go before or after this point.

1 Answer 1

1

turf.js method turf.nearestPointOnLine returns closest point on line to the given point as feature, where property index tells on which line string segment point was found. Segments are numbered starting from 0, this denoting segment from first to second point on line string.

This means that if closest point was found on segment N, point has to be inserted after point with index N in line string coordinates array.

If we take that line string coordinates are stored in lineCoords variable and point coordinate is stored in pointCoords variable, then code for inserting point could look something like this:

var line = turf.lineString(lineCoords);
var point = turf.point(pointCoords);

var nearestPoint = turf.nearestPointOnLine(line, point);
var insertIndex = nearestPoint.properties.index;
lineCoords.splice(insertIndex + 1, 0, pointCoords);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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