Tyler
Tyler

Reputation: 119

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?

Upvotes: 6

Views: 4604

Answers (1)

Marcelo
Marcelo

Reputation: 9407

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:

Upvotes: 7

Related Questions