Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate "as the crow flies" distance php

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?

like image 426
Tyler Avatar asked Dec 12 '12 17:12

Tyler


People also ask

How can I find the distance between two points in PHP?

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 = $ ...

Can Google maps show as the crow flies?

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.


1 Answers

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:

like image 188
Marcelo Avatar answered Sep 20 '22 05:09

Marcelo