I am currently calculating the driving distance between two points on one of my wordpress websites inside of a function. I accomplish this using the google distance matrix by calling
wp_remote_get(
"http://maps.googleapis.com/maps/api/distancematrix/json?origins=".
urlencode($origin).
"&destinations=".
urlencode($destination).
"&sensor=false&units=imperial"
)
and then inserting the origins and destinations users have entered via a form into the url. Is it possible to use a similar approach to calculating an "as the crow flies" distance or do I have to rework my function?
php function distance($lat1, $lon1, $lat2, $lon2, $unit) { if (($lat1 == $lat2) && ($lon1 == $lon2)) { return 0; } else { $theta = $lon1 - $lon2; $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); $dist = acos($dist); $dist = rad2deg($dist); $miles = $ ...
Google will now let you fly as the crow does. According to The Atlantic City Lab: “Google Maps this week has updated with a fresh tool. Users can right-click on any location on a map, select 'measure distance,' click on another location, and see a line displaying the exact mileage between the two points.
Distance between 2 points: (lat1,lon1) to (lat2,lon2)
distance = acos(
cos(lat1 * (PI()/180)) *
cos(lon1 * (PI()/180)) *
cos(lat2 * (PI()/180)) *
cos(lon2 * (PI()/180))
+
cos(lat1 * (PI()/180)) *
sin(lon1 * (PI()/180)) *
cos(lat2 * (PI()/180)) *
sin(lon2 * (PI()/180))
+
sin(lat1 * (PI()/180)) *
sin(lat2 * (PI()/180))
) * 3959
3959 is the Earth radius in Miles. Replace this value with radius in KM, (or any other unit), to get results on the same unit.
You can verify your implementation by comparing to this worked example:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With