Skip to content

Instantly share code, notes, and snippets.

@mintbridge
Created January 23, 2011 20:08
Show Gist options
  • Save mintbridge/792388 to your computer and use it in GitHub Desktop.
Save mintbridge/792388 to your computer and use it in GitHub Desktop.
/*
function to create the sql for finding the distance between 2 lat/lng pairs
*/
//$unit = '6367.45';
//$unit = '3978';
function distance($lat_from, $lng_from, $lat_to, $lng_to, $unit = '3978') {
return ‘ROUND($unit * acos(sin(‘.$lat_from.’) * sin(‘.$lat_to.’) + cos(‘.$lat_from.’) * cos(‘.$lat_to.’) * cos(‘.$lng_from.’ - ‘.$lng_to.’)))’;
}
//Use it like this:
$latitude = '40.7397960';
$longitude = '-73.9979390';
$sql = "SELECT ".distance(deg2rad($latitude), deg2rad($longitude), deg2rad(`s`.`lat_rad`), deg2rad(`s`.`lng_rad`))." AS `distance` FROM `sometable` AS `s` WHERE ".distance(deg2rad($latitude), deg2rad($longitude), deg2rad(`s`.`lat_rad`), deg2rad(`s`.`lng_rad`))." < '".$max_distance."'";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment