Created
July 20, 2011 22:42
-
-
Save jeffery/1096112 to your computer and use it in GitHub Desktop.
MySQL Helper class for calculating Distances between to geo locations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class GeoLocator | |
{ | |
/** | |
* @var string | |
*/ | |
public static $tableGeoPostcodeSuburbState = 'geoAustralianLocations'; | |
const EARTH_RADIUS_KM = 6378.137; | |
const EARTH_RADIUS_MILE = 3963.191; | |
const KM_PER_LATITUDE = 111.325; // we use this value if we are dealing with degrees than radians | |
/** | |
* Get the Geo Proximity equation | |
* | |
* We are using the WGS 84 reference coordinate system which incidently is | |
* used by the Global Positioning System | |
* | |
* @param integer $locationLatitude | |
* @param integer $locationLongitude | |
* @param string $tableAlias | |
* @return string | |
*/ | |
public static function getProximityEquation( $locationLatitude, $locationLongitude, $tableAlias ) | |
{ | |
return " | |
ROUND( | |
( | |
" . GeoLocator::EARTH_RADIUS_KM . " * | |
ACOS( | |
( | |
SIN(PI() * {$locationLatitude} / 180) * | |
SIN(PI() * {$tableAlias}.geoLatitude / 180) | |
) + | |
( | |
COS(PI() * {$locationLatitude} /180) * | |
COS(PI() * {$tableAlias}.geoLatitude / 180) * | |
COS(PI() * {$tableAlias}.geoLongitude / 180 - PI() * {$locationLongitude} / 180) | |
) | |
) | |
), | |
2 | |
) | |
"; | |
} | |
/** | |
* Calculate the distance between latitude and longitude coordinates | |
* | |
* @param string $fromLatitude | |
* @param string $fromLongitude | |
* @param string $toLatitude | |
* @param string $toLongitude | |
* @return integer value in Kms | |
*/ | |
public static function calculateDistanceProximity($fromLatitude, $fromLongitude, $toLatitude, $toLongitude) | |
{ | |
return | |
round( | |
( | |
acos | |
( | |
( | |
sin(deg2rad($fromLatitude)) * | |
sin(deg2rad($toLatitude)) | |
) + | |
( | |
cos(deg2rad($fromLatitude)) * | |
cos(deg2rad($toLatitude)) * | |
cos(deg2rad($fromLongitude - $toLongitude)) | |
) | |
) * | |
GeoLocator::EARTH_RADIUS_KM | |
), | |
2 | |
); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment