Skip to content

Instantly share code, notes, and snippets.

@banksy89
Created May 25, 2012 14:06
Show Gist options
  • Save banksy89/2788320 to your computer and use it in GitHub Desktop.
Save banksy89/2788320 to your computer and use it in GitHub Desktop.
PHP - Function for getting Long and Lat from Google & a function for calculating distance between two Lat and Longs
function getLatLong ( $postcode )
{
$pc = preg_replace ( '/\s/', '', $postcode );
$pc = 'http://maps.google.com/maps/geo?q='.$pc.',+UK&output=csv&sensor=false';
$result = explode ( ",", file_get_contents ( $pc ) );
return array ( $result[ 2 ], $result[ 3 ] );
}
function getDistance( $custlat1, $custlong1, $lat, $long )
{
$distance = 4;
$pi80 = M_PI / 180;
$custlat1 *= $pi80;
$custlong1 *= $pi80;
$lat *= $pi80;
$long *= $pi80;
$r = 6372.797;
$dlat = $custlat1 - $lat;
$dlng = $custlong1 - $long;
$a = sin( $dlat / 2 ) * sin( $dlat / 2 ) + cos( $custlat1 ) * cos( $lat ) * sin( $dlng / 2 ) * sin( $dlng / 2 );
$c = 2 * atan2 ( sqrt( $a ), sqrt( 1 - $a ) );
// Distance in KM so we can work out the milage
$km = round( $r * $c, 2 );
// Now we have the distance in miles
$miles = round( $km * 0.621371192, 2 );
return $miles;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment