Get latitude and longitude points along a line between two points, by percentage

馋奶兔 提交于 2019-12-04 19:29:23

Warning : this works on a linear coordinates. As Ollie Jones mentioned, while this is a reasonable approximation for short distances (or for certain cases depending on your projection), this won't work for long distance or if you want a very accurate point at percent

The function you are looking for is pointAtPercent. Red is the start point (your center circle) and green the end point (your end circles)

var ctx = document.getElementById("myChart").getContext("2d");

function drawPoint(color, point) {
    ctx.fillStyle = color;
    ctx.beginPath();
    ctx.arc(point.x, point.y, 5, 0, 2 * Math.PI, false);
    ctx.fill();
}

function drawLine(point1, point2) {
    ctx.strokeStyle = 'gray';
    ctx.setLineDash([5, 5]);    
    ctx.beginPath();
    ctx.moveTo(point1.x, point1.y);
    ctx.lineTo(point2.x, point2.y);
    ctx.stroke();    
}


function pointAtPercent(p0, p1, percent) {
    drawPoint('red', p0);
    drawPoint('green', p1);
    drawLine(p0, p1);

    var x;
    if (p0.x !== p1.x)
        x = p0.x + percent * (p1.x - p0.x);
    else
        x = p0.x;

    var y;
    if (p0.y !== p1.y)
        y = p0.y + percent * (p1.y - p0.y);
    else
        y = p0.y;

    var p = {
        x: x,
        y: y
    };
    drawPoint('blue', p);

    return p;
}


pointAtPercent({ x: 50, y: 25 }, { x: 200, y: 300 }, 0.2)
pointAtPercent({ x: 150, y: 25 }, { x: 300, y: 100 }, 0.6)
pointAtPercent({ x: 650, y: 300 }, { x: 100, y: 400 }, 0.4)

Fiddle - https://jsfiddle.net/goev47aL/

See this page for your different equations. http://www.movable-type.co.uk/scripts/latlong.html

  1. Get distance and bearing from origin to destination.
  2. Convert percentage to distance in the applicable units.
  3. Use bearing from #1, distance from #2 and origin to get resulting location

    function destination(lat, lon, bearing, distance) {
        var R = 6378.1, lat, lon, latDest, lonDest;
    
        // convert to radians
        lat = lat * (Math.PI / 180);
        lon = lon * (Math.PI / 180);
        bearing = bearing * (Math.PI / 180);
    
        latDest = Math.asin(Math.sin(lat) * Math.cos(distance / R) +
            Math.cos(lat) * Math.sin(distance / R) * Math.cos(bearing));
    
        lonDest = lon + Math.atan2(Math.sin(bearing) * Math.sin(distance / R) * Math.cos(lat),
                Math.cos(distance / R) - Math.sin(lat) * Math.sin(latDest));
    
        return [latDest * (180 / Math.PI), lonDest * (180 / Math.PI)];
    }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!