Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Haversine formula (PHP/MySQL)
* 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
You can’t perform that action at this time.