Last active
September 27, 2023 16:23
-
-
Save PhillipMwaniki/194b4bc3af9ec12c9427c6d043d9b9e4 to your computer and use it in GitHub Desktop.
Get coordinates for a bounding box by providing center coordinates and a distance
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 | |
/** | |
* This function was inspired by this mysql tutorial https://www.youtube.com/watch?v=QgnCB8X_sN4 | |
* @param float $latitude | |
* @param float $longitude | |
* @param int $bearing 0 = north, 180 = south, 90 = east, 270 = west | |
* @param int $distance m = miles or km = kilometer | |
* @param string $distance_unit | |
* | |
* | |
* @return array | |
*/ | |
public function getBoundingBoxCoords(float $latitude, float $longitude, int $bearing, int $distance, string $distance_unit = 'km'): array | |
{ | |
$radius = match ($distance_unit) { | |
'm' => 3963.1676, | |
default => 6378.1, | |
}; | |
// New latitude in degrees. | |
$new_latitude = rad2deg(asin(sin(deg2rad($latitude)) * cos($distance / $radius) + cos(deg2rad($latitude)) * sin($distance / $radius) * cos(deg2rad($bearing)))); | |
// New longitude in degrees. | |
$new_longitude = rad2deg(deg2rad($longitude) + atan2(sin(deg2rad($bearing)) * sin($distance / $radius) * cos(deg2rad($latitude)), cos($distance / $radius) - sin(deg2rad($latitude)) * sin(deg2rad($new_latitude)))); | |
$coord = []; | |
$coord['lat'] = $new_latitude; | |
$coord['lng'] = $new_longitude; | |
return $coord; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment