Search code examples
phpmysqlpostal-code

Canadian Postal Codes Radius


I am using the following scripting that I found on the net to grab all postal codes between a given set coordinates.

When using it my concern is that when some postal codes being grab are greater than the distance entered; not by much - about 20 KM off.

function GetPostalCodes($latitude, $longitude, $range) {
    $radius = 3959;
    $north = rad2deg(asin(sin(deg2rad($latitude)) * cos($range / $radius) + cos(deg2rad($latitude)) * sin($range / $radius) * cos(deg2rad(0))));
    $south = rad2deg(asin(sin(deg2rad($latitude)) * cos($range / $radius) + cos(deg2rad($latitude)) * sin($range / $radius) * cos(deg2rad(180))));
    $east = rad2deg(deg2rad($longitude) + atan2(sin(deg2rad(90)) * sin($range / $radius) * cos(deg2rad($latitude)), cos($range / $radius) - sin(deg2rad($latitude)) * sin(deg2rad($north))));
    $west = rad2deg(deg2rad($longitude) + atan2(sin(deg2rad(270)) * sin($range / $radius) * cos(deg2rad($latitude)), cos($range / $radius) - sin(deg2rad($latitude)) * sin(deg2rad($north))));
    $return = DBSelectAllArrays("SELECT postal FROM postalcodes WHERE (latitude <= $north AND latitude >= $south AND longitude <= $east AND longitude >= $west)");
    krsort($return);
    if (empty($return)) return false;
    return $return;
}

Is there something I am missing to get a more accurate result?


Solution

  • Given your comments:

    $radius = 6371.0; // mean radius of Earth in km
    

    This is taken from wikipedia, but I've seen it within a +/- 3km tolerance from other sources. I began to question whether you were using great circle distance calculations, but this is more important for accuracy over longer distances due to the curvature of the earths surface.