Page 1 of 1

Zip Code Radius Calculations

Posted: Fri Feb 18, 2005 10:19 am
by comtek
Does ayone know of any zip code radius search information that relates to PHP and MySQL?

I have found several articles but mainly related to Cold Fusion

I want to build a script that will do a radius search and return all the zip codes withing the given distance.

I have a copy of the US zip codes containing State, City, Longitude, and Latitude. I also have informatin on the Haversine Formula... I just don't undertand it and how to use it in PHP and MySQL.

Any help will be greatly appreciated.

Posted: Fri Feb 18, 2005 10:23 am
by feyd
if you have long-lat specs for all regions, it's somewhat simple math. If you don't have this information, you need to convert the data you have to long-lat coords in order to perform a radial inclusion.

I'm pretty sure we've talked about this a bit before on the forums.

Posted: Fri Feb 18, 2005 11:23 am
by comtek
I have been searching, but have only found one or two relevant post and neither one had very much information.

My goal is to list all users that are within X miles from the user initiating the search, return the information sorted from closest to farthest.

Posted: Fri Feb 18, 2005 11:51 am
by jonemo
did you find ready cold fusion scripts? what do you not unterstand about the algorithm you mentioned?

Posted: Fri Feb 18, 2005 1:11 pm
by comtek
Yes, the CF script appears to be complete.

here is the db query code:


Code: Select all

<cfquery datasource="#dsname#" name="getlocs">
    SELECT zipcode, latitude, longitude, statename, city,
    ROUND((ACOS((SIN(#passedzip.latitude#/57.2958) * SIN(latitude/57.2958)) +
    (COS(#passedzip.latitude#/57.2958) * COS(latitude/57.2958) *
    COS(longitude/57.2958 - #passedzip.longitude#/57.2958))))
    * 3963) AS distance
    FROM zipcodes
    WHERE (latitude >= #passedzip.latitude# - (#passedradius#/111))
    And (latitude <= #passedzip.latitude# + (#passedradius#/111))
    AND (longitude >= #passedzip.longitude# - (#passedradius#/111))
    AND (longitude <= #passedzip.longitude# + (#passedradius#/111))
    ORDER BY distance
</cfquery>

How would you convert that to PHP and MySQL commands?

.

Posted: Fri Feb 18, 2005 1:12 pm
by comtek
Oh, the constant 111 should be changed to 69 for Miles.

Posted: Fri Feb 18, 2005 7:30 pm
by smpdawg
Here is a php class to do zip code disctance calculations and a database to go with it.

http://phpclasses.spunge.org/browse/package/522.html

or the authors site

http://www.sanisoft.com/ziploc/