Skip to content

Instantly share code, notes, and snippets.

@jeffery
Created July 20, 2011 22:42
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 jeffery/1096112 to your computer and use it in GitHub Desktop.
Save jeffery/1096112 to your computer and use it in GitHub Desktop.
MySQL Helper class for calculating Distances between to geo locations
<?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