Search code examples
javascriptgeometry2dturfjsflatten-js

2D geometry calculation - on flat surface


I am trying to do some geometry calculation (e.g distance from point to line) on 2D planar planes.

Currently investigating turfjs to calculate distance from point to line.


Code

distance.js:

// hello
var turf = require('@turf/turf')

init();

// init,
function init() {
    distance();
}

function distance() {
    // line
    let line = turf.lineString([
    [0, 0],
    [3, 4]
    ]);
    console.log(line);

    // point
    let point = turf.point([3, 0]);
    console.log(point);

    // calculate distance from point to line, using planar,
    let dis = turf.pointToLineDistance(point, line, {
    units: 'degrees',
    method: 'planar'
    });
    console.log("distance: %f", dis);
}

Output

distance: 2.398995395932417

If I change point to [30, 0] and line to [0, 0], [30, 40], then the output is:

distance: 25.741472914575986

The program is using degrees as unit, and planar as method.

The expected results are 2.4 and 24, but it's not.


Question

  • So, does that means those points are on a curved surface, instead of a flat plane?
  • Is it possible to define points & lines & polygons in flat plane, instead of the curved surface?
  • If not, then it there another similar tool to perform this task?

Solution

  • If you look at turf.js source code for point to line distance, you'll see that it calculates planar distances along a rhumb line, and that's not what you would expect in planar geometry.

    To achieve what you want, you could implement the equation yourself, something like

    function pointToLineDistance(line, p0) {
        var p1 = line[0],
            p2 = line[1];
    
        var x0 = p0[0], y0 = p0[1],
            x1 = p1[0], y1 = p1[1],
            x2 = p2[0], y2 = p2[1]
    
    
        return Math.abs(
            (y2 - y1) * x0
            - (x2 - x1) * y0
            + x2 * y1
            - y2 * x1
        ) 
        /
        Math.sqrt(
            (y2 - y1) * (y2 - y1)
            +
            (x2 - x1) * (x2 - x1)
        );
    }
    
    console.log(
        pointToLineDistance([[0, 0], [3, 4]], [3, 0]),
        pointToLineDistance([[0, 0], [30, 40]], [30, 0]),
    );

    Or if you prefer a library, something like flatten.js could help you :

    let Flatten = require('flatten-js');
    
    let {point, line} = Flatten;
    
    let l = line(point(0, 0), point(3, 4));
    let p = point(3, 0)
    let d = p.distanceTo(l);
    
    console.log(d[0]);