MySQL & PHP: Get distance between two coordinates in miles/kilometers

Getting the distance in miles or kilometers between two coordinates is not impossible in MySQL, the query is just really nasty looking!

It is easier to explain with an example case, so lets use Dallas and Los Angeles. The coodinates are as follows (latitude, longitude).

Dallas: 32.782778 N, -96.803889 W
Los Angeles: 34.617778 N, -117.833611 W

The query to get the distance between the two points in miles is this beast:

-- Change 3959 to 6371 to get the distance in kilometers
 
SELECT (
	3959 *
	acos(
		cos(radians(32.782778)) *
		cos(radians(34.617778)) *
		cos(radians(-117.833611) - radians(-96.803889)) +
		sin(radians(32.782778)) *
		sin(radians(34.617778))
	)
) AS distance

If you execute that MySQL query, you will get 1213.32574928664 for the distance in miles between the two points.

You can also do the same thing in pure PHP.

<?php
 
$coords = array(
    'DFW' => array('lat'=>32.782778, 'long'=>-96.803889),
    'LAX' => array('lat'=>34.617778, 'long'=>-117.833611),
);
 
// Change 3959 to 6371 to get the distance in kilometers
 
$distance = (3959 * acos(
        cos(deg2rad($coords['DFW']['lat'])) *
        cos(deg2rad($coords['LAX']['lat'])) *
        cos(deg2rad($coords['LAX']['long']) - deg2rad($coords['DFW']['long'])) +
        sin(deg2rad($coords['DFW']['lat'])) *
        sin(deg2rad($coords['LAX']['lat']))
    )
);
 
var_dump($distance);
 
?>

What about kilometers?

Do you see that mysterious number (3959) in the above code samples? That is the earth’s radius in miles. Change that number to 6371 and you will get your distance in kilometers.

I built a simple tool to calculate distances between two points. Check it out!

Comments are closed.