# [ACCEPTED]-Calculating distance between zip codes in PHP-distance

Score: 26

This is mike's answer with some annotations 2 for the magic numbers. It seemed to work fine for me 1 for some test data:

``````function calc_distance(\$point1, \$point2)
{

\$distance = (\$radius * pi() * sqrt(
(\$point1['lat'] - \$point2['lat'])
* (\$point1['lat'] - \$point2['lat'])
+ cos(\$point1['lat'] / \$deg_per_rad)  // Convert these to
* (\$point1['long'] - \$point2['long'])
* (\$point1['long'] - \$point2['long'])
) / 180);

return \$distance;  // Returned using the units used for \$radius.
}
``````
Score: 7

It can be done with just maths...

``````function calc_distance(\$point1, \$point2)
{
\$distance = (3958 * 3.1415926 * sqrt(
(\$point1['lat'] - \$point2['lat'])
* (\$point1['lat'] - \$point2['lat'])
+ cos(\$point1['lat'] / 57.29578)
* cos(\$point2['lat'] / 57.29578)
* (\$point1['long'] - \$point2['long'])
* (\$point1['long'] - \$point2['long'])
) / 180);

return \$distance;
}
``````

0

Score: 7

Check out the Haversine formula for calculating great circle 2 distances between two points. Some more 1 samples can be found here

Haversine formula:

• Δlat = lat2− lat1
• Δlong = long2− long1
• a = sin²(Δlat/2) + cos(lat1).cos(lat2).sin²(Δlong/2)
• c = 2.atan2(√a, √(1−a))
• d = R.c

(Note that angles need to be in radians to pass to trig functions).

Score: 6

You can also try hitting a web service to 2 calc the distance. Let someone else do 1 the heavy lifting.

https://www.zipcodeapi.com/API#distance

Score: 1

In your zip table you need to grab the coordinates 13 (lat,long) for the two points for which 12 you want to get the distance.

You can then 11 either calculate the distance right in the 10 SQL or with PHP. Both methods are outlined 9 in this post:

http://dev.strategystar.net/2011/10/mysql-php-get-distance-between-two-coordinates-in-miles-kilometers/

The calculation in the example 8 is based on the formula already discussed 7 in this thread. It provides the radius for 6 the earth in both miles and kilometers so 5 it will allow you to get the distance between 4 two points in both units.

The link above 3 is great because the method for calculation 2 does not include any magic numbers, just 1 the radius of the earth!

More Related questions