Calculate the Distance Between Two Points in PHP

There are a lot of applications where it is useful to know the distance between two latitude longitude coordinates. Here’s a pair of PHP functions that make the calculation easy.

In the first, we find the distance between the two points in meters by assuming that the Earth is a perfectly round sphere with a radius of 6,371,008 meters. (Note that the Earth isn’t actually a perfect sphere; its radius at the poles is about 21 meters shorter than its radius at the equator. This will result in very slight inaccuracies in our calculations.)

In the second, we convert from meters to miles, yards, feet, and kilometers so that you can get your distance in whatever units are needed.

Here they are:

<?php

function get_meters_between_points($latitude1, $longitude1, $latitude2, $longitude2) {
	if (($latitude1 == $latitude2) && ($longitude1 == $longitude2)) { return 0; } // distance is zero because they're the same point
	$p1 = deg2rad($latitude1);
	$p2 = deg2rad($latitude2);
	$dp = deg2rad($latitude2 - $latitude1);
	$dl = deg2rad($longitude2 - $longitude1);
	$a = (sin($dp/2) * sin($dp/2)) + (cos($p1) * cos($p2) * sin($dl/2) * sin($dl/2));
	$c = 2 * atan2(sqrt($a),sqrt(1-$a));
	$r = 6371008; // Earth's average radius, in meters
	$d = $r * $c;
	return $d; // distance, in meters
}

function get_distance_between_points($latitude1, $longitude1, $latitude2, $longitude2) {
	$meters = get_meters_between_points($latitude1, $longitude1, $latitude2, $longitude2);
	$kilometers = $meters / 1000;
	$miles = $meters / 1609.34;
	$yards = $miles * 1760;
	$feet = $miles * 5280;
	return compact('miles','feet','yards','kilometers','meters');
}

?>

Here’s an example of the function in action, using two coordinates in New York City:

$point1 = array(40.713008, -74.013169);
$point2 = array(40.829643, -73.926175);
$distance = get_distance_between_points($point1['0'], $point1['1'], $point2['0'], $point2['1']);
echo '<p>The two points are '.round($distance['miles'],2).' miles apart.</p>';

That example tells you that Yankee Stadium is 9.26 miles away from One World Trade Center (as the crow flies, if there weren’t all those big buildings in the way).


Comments

Loading…

This post was first published on April 26th, 2011 and last updated on September 7th, 2017 by Robert James Reese in the following categories: Maps and PHP Before using any of the code or other content in this post, you must read and agree to our terms of use.