[ACCEPTED]-Calculating distance between zip codes in PHP-distance
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)
{
$radius = 3958; // Earth's radius (miles)
$deg_per_rad = 57.29578; // Number of degrees/radian (for conversion)
$distance = ($radius * pi() * sqrt(
($point1['lat'] - $point2['lat'])
* ($point1['lat'] - $point2['lat'])
+ cos($point1['lat'] / $deg_per_rad) // Convert these to
* cos($point2['lat'] / $deg_per_rad) // radians for cos()
* ($point1['long'] - $point2['long'])
* ($point1['long'] - $point2['long'])
) / 180);
return $distance; // Returned using the units used for $radius.
}
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
Check out the Haversine formula for calculating great circle 2 distances between two points. Some more 1 samples can be found here
Haversine formula:
- R = earth’s radius (mean radius = 6,371km)
- Δ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).
You can also try hitting a web service to 2 calc the distance. Let someone else do 1 the heavy lifting.
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:
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
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.