Created
February 14, 2023 18:42
-
-
Save mafalb/de4d3424ae4755f866dd38c1a30eb407 to your computer and use it in GitHub Desktop.
lat/long distance and square calculation
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 distance($latFrom, $lonFrom, $latTo, $lonTo) { | |
$earthRadius = 6371000; // in meter | |
// convert from degrees to radians | |
$latFrom = deg2rad($latFrom); | |
$lonFrom = deg2rad($lonFrom); | |
$latTo = deg2rad($latTo); | |
$lonTo = deg2rad($lonTo); | |
$latDelta = $latTo - $latFrom; | |
$lonDelta = $lonTo - $lonFrom; | |
$angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) + | |
cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2))); | |
return $angle * $earthRadius; | |
} | |
function square($lat) { | |
$earthRadius = 6371000; // in meter | |
// convert from degrees to radians | |
$lat = deg2rad($lat); | |
$latDelta = 0; | |
$lonDelta = M_PI*1.0; | |
$angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) + | |
cos($lat) * cos($lat) * pow(sin($lonDelta / 2), 2))); | |
$one_degree = $angle * $earthRadius / 180; | |
$lon = 1 / ($one_degree / 12000); | |
$lat = 1 / (111000 / 12000); | |
return [$lat, $lon]; | |
} | |
print(distance(0.0, 0.0, 0.0, -180.0) . "\n"); | |
print(distance(50.03, 8.48, 50.03, 8.62) . "\n\n"); | |
print_r(square(0.0)); | |
print_r(square(50.03)); | |
print("... WHERE lat >" . (50.03 - square(50.03)[0]/2) . " AND lat <" . (50.03 + square(50.03)[0]/2) . "...\n"); | |
print("... WHERE lon >" . (8.54 - square(50.03)[1]/2) . " AND lon <" . (8.54 + square(50.03)[1]/2) . "...\n"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment