-
-
Save fhferreira/ff59a6523cf9d0df1633 to your computer and use it in GitHub Desktop.
Haversine formula (PHP/MySQL)
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
/** | |
* Generates the string for the Haversine function. We assume that the `zipcode`, `latitude`, | |
* and `longitude` columns are named accordingly. We are also not doing much error-checking | |
* here; this is a simple text cruncher to make things prettier. | |
* We may also be integrating some extra SQL in, passed in via the $extra parameter | |
* | |
* @param string $table The table to search in | |
* @param float $lat The latitude part of the reference coordinates | |
* @param float $lng The longitude part of the reference coordinates | |
* @param int $radius The radius to search within | |
* @param string $extra Some extra SQL for the city/state part of the search | |
* | |
* @return string Returns an SQL query as a string | |
* | |
**/ | |
private function _haversine_sql($table,$lat,$lng,$radius,$extra = '') { | |
$output = "SELECT distinct *, | |
( 3959 * acos( cos( radians( {$lat} ) ) * cos( radians( `latitude` ) ) * cos( radians( `longitude` ) - radians( {$lng} ) ) + sin( radians( {$lat} ) ) * sin( radians( `latitude` ) ) ) ) AS distance | |
FROM `{$table}` HAVING distance <= {$radius} {$extra} | |
ORDER BY distance;"; | |
return $output; | |
} // end _haversine_sql($table,$lat,$lng,$radius,$extra = '') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment