I have experimented with some of the distance calculation I have found on some development sites for zip codes.
I can understand that the calculations aren't entirely accurate but the results I am getting are way off.
I punch in my zip code and set a radius of 30 miles. When I submit I get two zip codes from Oklahoma. I live in Texas right along the southeast coast of Houston and Oklahoma shouldn't be coming up. I get a bunch more zip codes within Texas and I have a hunch some of those are not within 30 mile radius.
Here is my PHP code:
<?php
function great_circle_distance($lat1, $lat2, $lon1, $lon2)
{
define('EARTH_RADIUS', 3959);
/* Convert all the degrees to radians */
$lat1 = deg_to_rad($lat1);
$lon1 = deg_to_rad($lon1);
$lat2 = deg_to_rad($lat2);
$lon2 = deg_to_rad($lon2);
/* Find the deltas */
$delta_lat = $lat2 - $lat1;
$delta_lon = $lon2 - $lon1;
/* Find the Great Circle distance */
$temp = pow(sin($delta_lat/2.0), 2) + cos($lat1) * cos($lat2) * pow(sin($delta_lon/2.0), 2);
$distance = EARTH_RADIUS * (2 * atan2(sqrt($temp), sqrt(1-$temp)));
return $distance;
}
function deg_to_rad($deg)
{
$radians = 0.0;
$radians = $deg * M_PI/180.0;
return($radians);
}
$sql = @mysql_connect('blah', 'blah', 'blah')
or die("<p>Unable to connect to MySQL server.<br>\nReason: " . mysql_error() . "</p>\n");
@mysql_select_db('somedb')
or die("<p>Unable to select database.<br>\nReason: " . mysql_error() . "</p>\n");
$zipcode = 77777;
$state = 'TX';
$radius = 30;
$result = @mysql_query("SELECT longitude, latitude FROM locations WHERE zipcode='$zipcode' AND state='$state'", $sql)
or die("<p>Unable to query database.<br>\nReason: " . mysql_error() . "</p>\n");
echo "<p>\n";
if (mysql_num_rows($result) == 1) {
$row = mysql_fetch_array($result);
$lon1 = $row[0];
$lat1 = $row[1];
printf("\tLongitude: %f, Latitude: %f<br>\n", $lon1, $lat1);
$result = @mysql_query("SELECT * FROM locations", $sql)
or die("<p>Unable to query database.<br>\nReason: " . mysql_error() . "</p>\n");
if (mysql_num_rows($result) > 0) {
echo "<p>\n";
while ($row = mysql_fetch_array($result)) {
$distance = great_circle_distance($lat1, $row[3], $lon1, $row[2]);
if ($distance <= $radius)
echo "Match - ZipCode: $row[0], State: $row[1], Longitude: $row[2], Latitude: $row[3], Distance: $distance miles<br>\n";
}
echo "</p>\n";
}
else
echo "<p>No results found.</p>\n";
}
else
echo "<p>No single result found.</p>\n";
echo "</p>\n";
mysql_free_result($result);
mysql_close($sql);
?>
I changed the set zip code for privacy reasons. The only thing that is not accurate are the latitude and longitude decimals I imported into my mysql database. I set the lat/lon as floats and they got rounded by like .000005 or so. I don't see how this could cause Oklahoma to show up when it's hundreds of miles away from me.
I plan on migrating the distance calculation to a SQL statement but what's up with this PHP code? Any ideas please?
Thanks in advance.