Skip to main content

Distance of two Geo-Points in PHP & Python

·168 words·1 min

I needed to calculate the distance between two Geo-Points using PHP.

Using Haversine formula you get to this function, where you enter lat1, long1, lat2, long2 and it will give the distance in Km.

In case you want to show the distance in Miles, simply change the Earth radius to 3956.

PHP:

function distance($lat1, $long1, $lat2, $long2) {
  	$R = 6371; // Earth Radius in Km
	$dLat = deg2rad($lat2-$lat1);
	$dLong = deg2rad($long2-$long1);
	$lat1 = deg2rad($lat1);
	$lat2 = deg2rad($lat2);

	$a = sin($dLat/2)*sin($dLat/2) + sin($dLong/2)*sin($dLong/2)*cos($lat1)*cos($lat2);
	$c = 2 * atan2(sqrt($a),sqrt(1-$a));
	$d = $R * $c;
	// Return with the distance
	return $d;
}

Python

import math

def distance(lat1, long1, lat2, long2):
  R = 6371 # Earth Radius in Km
	dLat = math.radians(lat2 - lat1) # Convert Degrees 2 Radians
	dLong = math.radians(long2 - long1)
	lat1 = math.radians(lat1)
	lat2 = math.radians(lat2)
	a = math.sin(dLat/2) * math.sin(dLat/2) + math.sin(dLong/2) * math.sin(dLong/2) * math.cos(lat1) * math.cos(lat2)
	c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
	d = R * c
	return d

Hope it helps someone!