I am trying to get zipcodes within a radius of 160km of the provided latitude/longitude coordinates. I already have a database of zipcodes, latitudes & longitudes, my problem is calculate the radius.
I have been looking at examples of how to do this, and this is what I came up with. But evidently something is wrong, because I'm getting distances that are ~9000km away according to the $dist variable.
public function getClose($latitude, $longitude) {
$latitudes = [floor($latitude)-2, ceil($latitude)+2];
$locations = Zipcode::whereBetween('latitude', $latitudes)->get();
foreach ($locations as $location) {
$venueLat = $location->latitude;
$venueLng = $location->longititude;
$latDistance = deg2rad($latitude - $venueLat);
$lngDistance = deg2rad($longitude - $venueLng);
$a = (sin($latDistance / 2) * sin($latDistance / 2)) + (cos(deg2rad($latitude))) * (cos(deg2rad($venueLat))) * (sin($lngDistance / 2)) * (sin($lngDistance / 2));
$c = 2 * atan2(sqrt($a), sqrt(1 - $a));
// Distance between 2 points in km. 6371 = Earths radius
$dist = 6371 * $c;
var_dump($dist); // This is the line saying it's about 9000km away
if ($dist < 160){
var_dump($location->zip);
}
}
}
That code was mostly based on this answer on a related question: https://stackoverflow.com/a/18465217
But, obviously something didn't translate right, or I misunderstood something. Any help would be vastly appreciated!