B
B
BonBon Slick2020-08-07 09:12:27
Mathematics
BonBon Slick, 2020-08-07 09:12:27

Calculate the distance between two coordinates in meters?

export const distanceBetweenCoords = (lat1, lon1, lat2, lon2, unit = 'K') => {
    if ((
            lat1 === lat2
        ) &&
        (
            lon1 === lon2
        )) {
        return 0;
    }
    const radlat1 = Math.PI * lat1 / 180;
    const radlat2 = Math.PI * lat2 / 180;
    const theta = lon1 - lon2;
    const radtheta = Math.PI * theta / 180;
    let dist = Math.sin(radlat1) *
               Math.sin(radlat2) +
               Math.cos(radlat1) *
               Math.cos(radlat2) *
               Math.cos(radtheta);
    if (dist > 1) {
        dist = 1;
    }
    dist = Math.acos(dist);
    dist = dist * 180 / Math.PI;
    dist = dist * 60 * 1.1515;
    //  'M' is statute miles (default)
    // 'K' is kilometers
    // 'N' is nautical miles
    if (unit === 'K') {
        dist = dist * 1.609344;
    }
    if (unit === 'N') {
        dist = dist * 0.8684;
    }
    return dist;
};


I correctly understand that it is necessary to remove the multiplier * 1.1515;?

Because I don’t really understand cos and sines, why and why do we multiply by 180 and 60.

const R = 6371e3; // metres
    const φ1 = lat1 * Math.PI/180; // φ, λ in radians
    const φ2 = lat2 * Math.PI/180;
    const Δφ = (lat2-lat1) * Math.PI/180;
    const Δλ = (lon2-lon1) * Math.PI/180;

    const a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +
              Math.cos(φ1) * Math.cos(φ2) *
              Math.sin(Δλ/2) * Math.sin(Δλ/2);
    let dist = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

    // const d = R * c; // in metres

    if (unit.toLowerCase() === 'm') {
        dist = R * c;
    }
    if (unit.toLowerCase() === 'k') {
        dist = R * c / 1000;
    }


Both scripts always return 0. For real coordinates, which the online calculator gives out the distance.

What's wrong?

Using online calculators you can get even in SM, that would be even better.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question