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

News Author


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

Flight Map Europe With Great Circle Distance

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

That’s an attention-grabbing begin however it doesn’t apply with Geography because the 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. For those who use some sort of easy triangulation equation, it might measure distance precisely in a single location and terribly flawed within the different, due to the curvature of the Earth.

Nice Circle Distance

The routes which might be traveled lengthy distances across the Earth are referred to as the Nice Circle Distance. That’s… the shortest distance between two factors on a sphere is totally 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 acquired a tough calculation.

Right here’s a implausible video rationalization of how Nice Circles work.

The Haversine System

The space utilizing the curvature of the Earth is integrated within the Haversine system, which makes use of trigonometry to permit for the curvature of the earth. Once you’re discovering the space 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 seen they’re arched? That’s as a result of it’s shorter to fly in an arch between two factors than on to the placement.

PHP: Calculate Distance Between 2 Factors of Latitude and Longitude

Right here’s the PHP system for calculating the space 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; 
  swap($unit) { 
    case 'miles': 
      break; 
    case 'kilometers' : 
      $distance = $distance * 1.609344; 
  } 
  return (spherical($distance,2)); 
}

The variables are:

  • $Latitude1 – a variable on your first location’s latitude.
  • $Longitude1 – a variable on your first location’s longitude
  • $Latitude2 – a variable on your second location’s latitude.
  • $Longitude2 – a variable on 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 on your first location’s latitude.
  • longitude1 – a variable on your first location’s longitude
  • latitude2 – a variable on your second location’s latitude.
  • longitude2 – a variable on 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 on your first location’s latitude.
  • longitude1 – a variable on your first location’s longitude
  • latitude2 – a variable on your second location’s latitude.
  • longitude2 – a variable on 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

Anyhow, right here’s the Python system for calculating the space between two factors (together with Mile vs. Kilometer conversion) rounded to 2 decimal locations. Credit score to my son, Invoice Karr who’s a Information 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 on your first location’s latitude.
  • longitude1 – a variable on your first location’s longitude
  • latitude2 – a variable on your second location’s latitude.
  • longitude2 – a variable on your second location’s longitude.
  • unit – the default being miles. This may be up to date or handed as kilometers.

MySQL: Retrieving All Data 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 might be 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 must 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 space that you simply want to discover all of the information much less or equal to.
  • desk – that is the desk… you’ll wish 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 Data 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 must 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 space that you simply want to discover all of the information much less or equal to.
  • desk – that is the desk… you’ll wish 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 areas throughout North America and it labored fantastically.

Microsoft SQL Server Geographic Distance: STDistance

For those who’re using Microsoft SQL Server, they provide their very own operate, STDistance for calculating the space between two factors utilizing the Geography information sort.

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.