-
-
Save loonies/792464 to your computer and use it in GitHub Desktop.
Calculating distance using latitude and longitude
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 | |
// http://www.movable-type.co.uk/scripts/latlong.html | |
// converted from JS to PHP | |
$d_lat = deg2rad($lat1 - $lat2); | |
$d_lon = deg2rad($lon1 - $lon2); | |
$lat1 = deg2rad($lat1); | |
$lat2 = deg2rad($lat2); | |
$r = 6371; // km | |
$a = sin($d_lat / 2) * sin($d_lat / 2) + | |
sin($d_lon / 2) * sin($d_lon / 2) * | |
cos($lat1) * cos($lat2); | |
$c = 2 * atan2(sqrt($a), sqrt(1 - $a)); | |
$d = $r * $c; |
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 | |
/** | |
* 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