Swipe left or right to navigate to next or previous post

distance between two location based on their latitude and longitude

14 Mar 2022 . category: Designing . Comments
#Maps #Tool #JavaScript #Frontend

Distance between two locations based on latitude and longitude

Wondering how to get the distance between the two location? This tools helps to get the distance between the location based on their latitude and longitude. This tools helps to get the distance in straight line.



Calculated distances

Steps to find the distance two location:
  1. Enter the comma separated latitude and longitude of the origin address like 27.12312, 85.123213
  2. Enter the comma separated latitude and longitude of the Destination address like 27.22312, 85.523213
  3. Hit Submit button. You will get the distance between the origin and destination in both miles and Kilometres

JavaScript formula to get the distance between two locations based on their latitude and longitude

    // Check if the lat lng is valid
    function isValidLatLng(latLngAddress){
        if(latLngAddress.length!==2){
            return false;
        }
        const lat = latLngAddress[0];
        const lng = latLngAddress[1];
        const isLatitudeValid =  isFinite(lat) && Math.abs(lat) <= 90;
        const isLongitudeValid = isFinite(lng) && Math.abs(lat) <= 180;
        return isLatitudeValid && isLongitudeValid;
    }

    // Change from degrees to Radians
    function degreesToRadians(degrees) {
        return (degrees * Math.PI)/180;
    }
    
    // Get the distance between lat and longitude
    function getDistanceBetweenLatLng(originLatitude, originLongitude, destinationLatitude, destinationLongitude) {
        if(originLatitude === destinationLatitude && originLongitude === destinationLongitude){
            return {
                'kms': 0,
                'miles': 0
            }
        }
        const radOriginLatitude = degreesToRadians(originLatitude);
        const radDestinationLatitude = degreesToRadians(destinationLatitude);
        const radtheta = degreesToRadians(originLongitude-destinationLongitude);
        let dist = Math.sin(radOriginLatitude) * Math.sin(radDestinationLatitude) + Math.cos(radOriginLatitude) * Math.cos(radDestinationLatitude) * Math.cos(radtheta);
        if (dist > 1) {
            dist = 1;
        }
        dist = Math.acos(dist);
        dist = dist * 180/Math.PI;
        dist = dist * 60 * 1.1515;
        return {
            'kms': parseFloat(dist * 1.609344).toFixed(2),
            'miles': parseFloat(dist * 0.868).toFixed(2)
        }
    }

Tapan B.K. | Full Stack Software Engineer

Tapan B.K. is Full Stack Software Engineer. In his spare time, Tapan likes to watch movies, visit new places.