Thursday, December 15, 2022
HomeMobile MarketingCalculating Distance Between 2 Places of Latitude & Longitude (PHP, Python, MySQL)

Calculating Distance Between 2 Places of Latitude & Longitude (PHP, Python, MySQL)


This month I’ve been programming fairly a bit in PHP and MySQL with respect to GIS. Snooping across the internet, I truly had a tough time discovering among the Geographic calculations to search out the gap between two places so I wished to share them right here.

Flight Map Europe With Great Circle Distance

The easy method of calculating a distance between two factors is utilizing the Pythagorean components to calculate the hypotenuse of a triangle (A² + B² = C²). This is named the Euclidean distance.

That’s an fascinating begin however it doesn’t apply with Geography for the reason that distance between strains of latitude and longitude are not equal distances aside. As you get nearer to the equator, strains of latitude get additional aside. In the event you use some type of easy triangulation equation, it could measure distance precisely in a single location and terribly improper within the different, due to the curvature of the Earth.

Nice Circle Distance

The routes which are traveled lengthy distances across the Earth are generally known as the Nice Circle Distance. That’s… the shortest distance between two factors on a sphere is completely different than the factors on a flat map. Mix that with the truth that the latitude and longitude strains aren’t equidistant… and also you’ve obtained a troublesome calculation.

Right here’s a improbable video clarification of how Nice Circles work.

The Haversine Formulation

The gap utilizing the curvature of the Earth is included within the Haversine components, which makes use of trigonometry to permit for the curvature of the earth. Once you’re discovering the gap between 2 locations on earth (because the crow flies), a straight line is absolutely an arc.

That is relevant in air flight – have you ever ever regarded on the precise map of flights and observed they’re arched? That’s as a result of it’s shorter to fly in an arch between two factors than on to the situation.

PHP: Calculate Distance Between 2 Factors of Latitude and Longitude

Right here’s the PHP components for calculating the gap between two factors (together with Mile vs. Kilometer conversion) rounded to 2 decimal locations.

operate getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2, $unit = 'miles') {
  $theta = $longitude1 - $longitude2; 
  $distance = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta))); 
  $distance = acos($distance); 
  $distance = rad2deg($distance); 
  $distance = $distance * 60 * 1.1515; 
  change($unit) { 
    case 'miles': 
      break; 
    case 'kilometers' : 
      $distance = $distance * 1.609344; 
  } 
  return (spherical($distance,2)); 
}

The variables are:

  • $Latitude1 – a variable in your first location’s latitude.
  • $Longitude1 – a variable in your first location’s longitude
  • $Latitude2 – a variable in your second location’s latitude.
  • $Longitude2 – a variable in your second location’s longitude.
  • $unit – the default being miles. This may be up to date or handed as kilometers.

Java: Calculate Distance Between 2 Factors of Latitude and Longitude

public static double getDistanceBetweenPointsNew(double latitude1, double longitude1, double latitude2, double longitude2, String unit) {
    double theta = longitude1 - longitude2;
    double distance = 60 * 1.1515 * (180/Math.PI) * Math.acos(
        Math.sin(latitude1 * (Math.PI/180)) * Math.sin(latitude2 * (Math.PI/180)) + 
        Math.cos(latitude1 * (Math.PI/180)) * Math.cos(latitude2 * (Math.PI/180)) * Math.cos(theta * (Math.PI/180))
    );
    if (unit.equals("miles")) {
        return Math.spherical(distance, 2);
    } else if (unit.equals("kilometers")) {
        return Math.spherical(distance * 1.609344, 2);
    } else {
        return 0;
    }
}

The variables are:

  • latitude1 – a variable in your first location’s latitude.
  • longitude1 – a variable in your first location’s longitude
  • latitude2 – a variable in your second location’s latitude.
  • longitude2 – a variable in your second location’s longitude.
  • unit – the default being miles. This may be up to date or handed as kilometers.

Javascript: Calculate Distance Between 2 Factors of Latitude and Longitude

operate getDistanceBetweenPoints(latitude1, longitude1, latitude2, longitude2, unit = 'miles') {
    let theta = longitude1 - longitude2;
    let distance = 60 * 1.1515 * (180/Math.PI) * Math.acos(
        Math.sin(latitude1 * (Math.PI/180)) * Math.sin(latitude2 * (Math.PI/180)) + 
        Math.cos(latitude1 * (Math.PI/180)) * Math.cos(latitude2 * (Math.PI/180)) * Math.cos(theta * (Math.PI/180))
    );
    if (unit == 'miles') {
        return Math.spherical(distance, 2);
    } else if (unit == 'kilometers') {
        return Math.spherical(distance * 1.609344, 2);
    }
}

The variables are:

  • latitude1 – a variable in your first location’s latitude.
  • longitude1 – a variable in your first location’s longitude
  • latitude2 – a variable in your second location’s latitude.
  • longitude2 – a variable in your second location’s longitude.
  • unit – the default being miles. This may be up to date or handed as kilometers.

Python: Calculate Distance Between 2 Factors of Latitude and Longitude

In any case, right here’s the Python components for calculating the gap between two factors (together with Mile vs. Kilometer conversion) rounded to 2 decimal locations. Credit score to my son, Invoice Karr who’s a Knowledge Scientist for OpenINSIGHTS, for the code.

from numpy import sin, cos, arccos, pi, spherical

def rad2deg(radians):
    levels = radians * 180 / pi
    return levels

def deg2rad(levels):
    radians = levels * pi / 180
    return radians

def getDistanceBetweenPointsNew(latitude1, longitude1, latitude2, longitude2, unit = 'miles'):
    
    theta = longitude1 - longitude2
    
    distance = 60 * 1.1515 * rad2deg(
        arccos(
            (sin(deg2rad(latitude1)) * sin(deg2rad(latitude2))) + 
            (cos(deg2rad(latitude1)) * cos(deg2rad(latitude2)) * cos(deg2rad(theta)))
        )
    )
    
    if unit == 'miles':
        return spherical(distance, 2)
    if unit == 'kilometers':
        return spherical(distance * 1.609344, 2)

The variables are:

  • latitude1 – a variable in your first location’s latitude.
  • longitude1 – a variable in your first location’s longitude
  • latitude2 – a variable in your second location’s latitude.
  • longitude2 – a variable in your second location’s longitude.
  • unit – the default being miles. This may be up to date or handed as kilometers.

MySQL: Retrieving All Information Inside A Vary By Calculating Distance In Miles Utilizing Latitude and Longitude

It’s additionally doable to make use of SQL to do a calculation to search out all information inside a selected distance. On this instance, I’m going to question MyTable in MySQL to search out all of the information which are lower than or equal to variable $distance (in Miles) to my location at $latitude and $longitude:

The question for retrieving all the information inside a selected distance by calculating distance in miles between two factors of latitude and longitude are:

$question = "SELECT *, (((acos(sin((".$latitude."*pi()/180)) * sin((`latitude`*pi()/180)) + cos((".$latitude."*pi()/180)) * cos((`latitude`*pi()/180)) * cos(((".$longitude."- `longitude`)*pi()/180)))) * 180/pi()) * 60 * 1.1515) as distance FROM `desk` WHERE distance <= ".$distance."

You’ll have to customise this:

  • $longitude – this can be a PHP variable the place I’m passing the longitude of the purpose.
  • $latitude – this can be a PHP variable the place I’m passing the longitude of the purpose.
  • $distance – that is the gap that you just want to discover all of the information much less or equal to.
  • desk – that is the desk… you’ll need to exchange that along with your desk identify.
  • latitude – that is the sector of your latitude.
  • longitude – that is the sector of your longitude.

MySQL: Retrieving All Information Inside A Vary By Calculating Distance In Kilometers Utilizing Latitude and Longitude

And right here’s the SQL question utilizing kilometers in MySQL:

$question = "SELECT *, (((acos(sin((".$latitude."*pi()/180)) * sin((`latitude`*pi()/180)) + cos((".$latitude."*pi()/180)) * cos((`latitude`*pi()/180)) * cos(((".$longitude."- `longitude`) * pi()/180)))) * 180/pi()) * 60 * 1.1515 * 1.609344) as distance FROM `desk` WHERE distance <= ".$distance."

You’ll have to customise this:

  • $longitude – this can be a PHP variable the place I’m passing the longitude of the purpose.
  • $latitude – this can be a PHP variable the place I’m passing the longitude of the purpose.
  • $distance – that is the gap that you just want to discover all of the information much less or equal to.
  • desk – that is the desk… you’ll need to exchange that along with your desk identify.
  • latitude – that is the sector of your latitude.
  • longitude – that is the sector of your longitude.

I utilized this code in an enterprise mapping platform that we utilized for a retail retailer with over 1,000 places throughout North America and it labored superbly.

Microsoft SQL Server Geographic Distance: STDistance

In the event you’re using Microsoft SQL Server, they provide their very own operate, STDistance for calculating the gap between two factors utilizing the Geography knowledge kind.

DECLARE @g geography;  
DECLARE @h geography;  
SET @g = geography::STGeomFromText('LINESTRING(-122.360 47.656, -122.343 47.656)', 4326);  
SET @h = geography::STGeomFromText('POINT(-122.34900 47.65100)', 4326);  
SELECT @g.STDistance(@h);  

Hat tip to Manash Sahoo, VP and Architect of Highbridge.



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments