I had an old script laying around that did a radius search given a certain zip code, and it would return a list of zip codes in the surrounding area. Lately I learned from a couple other Coldfusion developers that there is a much easier and faster way (though the query is more complex) to get a list of zip codes within a certain mile radius using some algebra I learned way back in high school. It's just a matter of knowing the right mysql functions to get it working (mssql should work for this too).
So I put it all together into a nice little package for you to take all the work out of searching and coding (since some examples don't work, and some are just so complex it's hard to figure out). So you don't have to go through the learning curve like I did, just download this package.
I created a CFC for doing the zip code radius search, and you can use this build a store locator. Just pass in the zipcode, datasource name where your zip code data is (unlike others I've included the data so you don't have to go looking for it), and radius. The CFC will return a query ordered by distance with zip code, city, and state. Sorry, but this only works for the United States, but I'm sure it can be adapted for any country that uses zip codes or postal codes as long as you have a database to go with it.
Here is a demonstration:
You can download the zip file here (around 2MB in size):
The zip code data is provided in mysql SQL format, CSV format, and XML format. You should be able to import the data into any database, but I can only guarantee this will work for mysql. I included a query specific to MSSQL but did not test to make sure it's working. Just pass in the argument "databasetype='mssql'" and it SHOULD work. I have not found a way to get it working for MS Access.
Can't download. Broken links :(
ReplyDeleteFixed the links. Sorry.
DeleteWorks great. Thanks for posting.
DeleteHi Jon,
ReplyDeleteFirst of all, let me say thanks for providing this code. I stumbled across your page here while looking for examples of zip code radius searches using CF. However, when I try running it, all I get returned is the zip code I originally entered. I also saw that your CFC contains a function named getdistance. I don't see that it's used by getradiuszips, so is it a separate function if one chooses to use it? Am I overlooking something? Thanks.
I get the following error. Any insight?
ReplyDeleteError Executing Database Query.
[Macromedia][SequeLink JDBC Driver][ODBC Socket][Microsoft][ODBC Microsoft Access Driver] Undefined function 'ACOS' in expression.
21 : AND (lat <= #qzip.lat# + (#radius#/111))
22 : AND (lon >= #qzip.lon# - (#radius#/111))
23 : AND (lon <= #qzip.lon# + (#radius#/111))
24 : ORDER BY distance
25 :
Nevermind - limitation of Access. Got it working in MySQL
Delete