Skip to content

Instantly share code, notes, and snippets.

@melvinmt
Created November 15, 2010 11:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save melvinmt/700270 to your computer and use it in GitHub Desktop.
Save melvinmt/700270 to your computer and use it in GitHub Desktop.
PHP class to calculate south-west and north-east bounds given a longitude, latitude and distance edit
<?php
/**
* @author Melvin Tercan
* @link http://twitter.com/melvinmt
**/
class Geo{
public static function bounds($mylat, $mylon, $dist = 100, $unit = 'km', $pyth_invert = true){
if(!$pyth_invert){
$dist = sqrt(pow($dist, 2) *2); // pythagoras
}elseif($pyth_invert){
$dist = sqrt($dist / 2); // inverted pythagoras
}else{
// $pyth_invert = NULL;
}
$earth_km_rad = 6371; // earth radius in km
switch ($unit){
case "m": // meters
$earth_rad = $earth_km_rad * 1000;
break;
case "mi": // miles
$earth_rad = $earth_km_rad * 0.621371192;
break;
case "yd": // yards
$earth_rad = $earth_km_rad * 1093.6133;
break;
case "ft": // feet
$earth_rad = $earth_km_rad * 3280.8399;
break;
case "in": // inches
$earth_rad = $earth_km_rad * 39370.0787;
break;
default: // km
$earth_rad = $earth_km_rad;
break;
}
// southwest
$sw = Geo::destination_point($mylat, $mylon, 225, $dist, $earth_rad);
// northeast
$ne = Geo::destination_point($mylat, $mylon, 45, $dist, $earth_rad);
return array('lat' => array(
'min' => $sw['lat'],
'max' => $ne['lat'],
),
'lon' => array(
'min' => $sw['lon'],
'max' => $ne['lon'],
),
'sw' => $sw,
'ne' => $ne,
'dist' => $dist
);
}
public static function destination_point($lat1, $lon1, $deg, $dist, $earth_rad = 6371){
$distance = $dist / $earth_rad;
$deg = deg2rad($deg);
$lat1 = deg2rad($lat1);
$lon1 = deg2rad($lon1);
$lat2 = asin( sin($lat1) * cos($dist) + cos($lat1) * sin($dist) * cos($deg) );
$lon2 = $lon1 + atan2( sin($deg) * sin($dist) * cos($lat1), cos($dist) - sin($lat1) * sin($lat2));
$lon2 = ( $lon2 + 3 * pi() ) % ( 2*pi() ) - pi();
return array('lat' => rad2deg($lat2), 'lon' => rad2deg($lon2));
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment