Turfjs / turf

A modular geospatial engine written in JavaScript and TypeScript

Home Page:https://turfjs.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Drawing a curved line from Point A to Point B

randomprogramming opened this issue · comments

I am re-opening the question #1218, as I do not believe that the question was solved. There still doesn't seem to be a solution to drawing a curved line from point A to point B, with both the start point and the end point perfectly aligned, and there are other people having this issue still. The points are always drifting away a bit:

image
function buildArcLine(origin: Geo, destination: Geo) {
    const start = [origin.longitude, origin.latitude];
    const end = [destination.longitude, destination.latitude];

    // Calculate the midpoint
    const midpoint = [(start[0] + end[0]) / 2, (start[1] + end[1]) / 2];

    // Calculate the vector between start and end points
    const lineVector = [end[0] - start[0], end[1] - start[1]];

    // Calculate the perpendicular vector
    const perpendicularVector = [-lineVector[1], lineVector[0]];

    // Normalize the perpendicular vector
    const length = Math.sqrt(perpendicularVector[0] ** 2 + perpendicularVector[1] ** 2);
    const normalizedPerpendicularVector = [
        length === 0 ? 0 : perpendicularVector[0] / length,
        length === 0 ? 0 : perpendicularVector[1] / length,
    ];

    // Scale the perpendicular vector to move the midpoint (adjust the scale factor as needed)
    const scale = 3; // Adjust this scale factor as needed
    const midAdjusted = [
        midpoint[0] + scale * normalizedPerpendicularVector[0],
        midpoint[1] + scale * normalizedPerpendicularVector[1],
    ];

    const line = lineString([start, midAdjusted, end]);

    const bezier = bezierSpline(line, { resolution: 15000 });

    return {
        type: "FeatureCollection",
        features: [bezier],
    };
}

With the help of GPT, I managed to type up this code which works pretty well. The curve still isn't perfect but at least the origin and destination points are correct.