Search code examples
c#.net-3.5geolocationlatitude-longitudezipcode

Given coordinates, how do I get all the Zip Codes within a 10 mile radius?


I have a location (latitude & longitude). How can I get a list of zipcodes that are either partially or fully within the 10 mile radius of my location?

The solution could be a call to a well known web service (google maps, bing maps, etc...) or a local database solution (the client has sql server 2005) or an algorithm.

I have seen the somewhat similar question, but all the answers there pretty much pertain to using SQL Server 2008 geography functionality which is unavailable to me.


Solution

  • Firstly, you'll need a database of all zipcodes and their corresponding latitudes and longitudes. In Australia, there are only a few thousand of these (and the information is easily available), however I assume it's probably a more difficult task in the US.

    Secondly, given you know where you are, and you know the radius you are looking for, you can look up all zipcodes that fall within that radius. Something simple written in PHP would be as follows: (apologies it's not in C#)

    function distanceFromTo($latitude1,$longitude1,$latitude2,$longitude2,$km){
      $latitude1  = deg2rad($latitude1);
      $longitude1 = deg2rad($longitude1);
      $latitude2  = deg2rad($latitude2);
      $longitude2 = deg2rad($longitude2);
      $delta_latitude  = $latitude2  - $latitude1;
      $delta_longitude = $longitude2 - $longitude1;
      $temp = pow(sin($delta_latitude/2.0),2) + cos($latitude1) * cos($latitude2) * pow(sin($delta_longitude/2.0),2);
      $earth_radius = 3956;
      $distance = $earth_radius * 2 * atan2(sqrt($temp),sqrt(1-$temp));
      if ($km)
        $distance = $distance * 1.609344;
      return $distance;
    }