Search code examples
javascriptvectorgeolocationmapslatitude-longitude

Draw a perpendicular line through middle of two long/lat points


Hello i'm currently trying to draw a line through two long/lat lines to create a triangle. So far i have manged to draw a line through but the line is not perpendicular and looks skewed. Here is my code:

    startPosition = [-0.17640, 51.426700];
    endPosition =  [0.17640, 51.796700];

    triangleSizeY = (endPosition [1] - startPosition[1]) / 6;
    /*subtract 
    end from start to work out direction and also use this divided by 6 to 
    get distance*/
    triangleSize *= -1;

    triangleSizeX = (endPosition [0] - startPosition[0]) / 6;
    /*subtract 
    end from start to work out direction and also use this divided by 6 to 
    get distance*/
    triangleSize *= -1;

    var cx = (startPosition[0] + endPosition[0]) / 2;
    var cy = (startPosition[1] + endPosition[1]) / 2;
    var dx = (endPosition[0] - startPosition[0]) / 2;
    var dy = (endPosition[1] - startPosition[1]) / 2;
    positions[0] = [midPoint[0] + triangleSizeX, midPoint[1] + 
    triangleSizeY];
    positions[1] = [cx - dy, cy + dx];
    positions[2] = [cx + dy, cy - dx];

This is what it looks like:

enter image description here


Solution

  • First, lat/lon are angular so you can not do linear type distances. The steps you need to take to solve this:

    1. Compute the distance between the 2 lat/lon pairs you want a perpendicular line from.
    2. Take half the distance computed from the above step to get you the midpoint range.
    3. Calculate the bearing between the 2 lat/lon pairs. (see reference below on computing a bearing from 2 lat/lon's)
    4. With the half distance and bearing, you can compute the lat/lon of the midpoint. This is called computing a lat/lon based on a range and bearing. (See the reference below.)
    5. Now you can go perpendicular from the midpoint by adding/subtracting 90 degrees from the bearing in step 3. Decide on a range you want to compute the new lat/lon from a range/bearing like in step 4.

    This site (https://www.movable-type.co.uk/scripts/latlong.html) has the calculations you need to do this. Also, since the distance is relatively small, you can use the Equirectangular approximation over Haversine for distance calculation.