Fri 26 Dec 2008
longitude and latitude distance calculation using php
Posted by Hawk under Dirty ScriptsLet Me Hear Your Thoughts >>
Creating a distance between cities using the geolite data that I’ve used in the the mapping IP-2-Location. If you look at longitude and latitude points in decimal format instead of the degrees:min:seconds then you can pretty much figure out how you calculate distance. Its the same way you do when you measure the distance between two points on a sphere.
Surprisingly, php has no support that I know of to convert degrees to radians, so I first built that, then the rest is just self explanatory.
“The world is a book and those who do not travel read only one page.” - St. Augustine
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | <?php // no native function in php4/5 function toRadians($degrees) { return $degrees * pi() / 180; } $lat1 = $_POST['lat1']; $lat2 = $_POST['lat2']; $lon1 = $_POST['lon1']; $lon2 = $_POST['lon2']; $R = 6371; // km radius of earth $dLat = toRadians($lat2-$lat1); $dLon = toRadians($lon2-$lon1); $a = sin($dLat/2) * sin($dLat/2) + cos(toRadians($lat1)) * cos(toRadians($lat2)) * sin($dLon/2) * sin($dLon/2); $ax = 1-$a; $c = 2 * atan2(sqrt($a), sqrt($ax)); $d = $R * $c; ?> <html> <body <div > <?= 'Distance:'.$d ? </div> <div> <form action="" method="post"> <fieldset><label>Lat1</label><input type="text" name="lat1" size=4></fieldset> <fieldset><label>Lat2</label><input type="text" name="lat2" size=4></fieldset> <fieldset><label>Lon1</label><input type="text" name="lon1" size=4></fieldset> <fieldset><label>Lon2</label><input type="text" name="lon2" size=4></fieldset> <input type="submit"> </form> </div> </body> </html> |