Monday, January 26, 2015

Nearby Zip Codes from Coordinates

You would need to create a reference table of zip codes and their corresponding geo-location. Then you could run a query against the table to return zip codes within a given radius of a given location.


For example, if you obtained a list of zip codes from here, the data already contains the relevant Latitude and Longitude of each zip code. Import the data, then add a computed persisted column to cast the Lat Long as a geography type. Finally, query all zip codes near the desired location, e.g. within 50 miles of Tampa, FL.



ALTER TABLE ZipCode ADD ZipGeo AS geography::Point(Latitude, Longitude, 4326) PERSISTED


DECLARE @yourLoc GEOGRAPHY = geography::Point(27.947222, -82.458611, 4326) /* Tampa, FL */
,@yourRadius FLOAT = 50 * 1609.34; /* miles to meters */

SELECT *
FROM ZipCode
WHERE @yourLoc.STDistance(ZipGeo) < @yourRadius;



Jason



No comments:

Post a Comment