NYCPHP Meetup

NYPHP.org

[nycphp-talk] Re: Search By Distance In Miles (Jeff Rigby)

Jeff Rigby jrigby at mac.com
Tue Oct 5 16:38:49 EDT 2004


Try this:

// Look up the original (Center of radius) in the zip table (Schema 
below)
         $query = "SELECT longw, latn FROM zips WHERE zipcode = '$zip'";
         $zip = $db->query($query);

  // Assign the longitude & latitude variables.
         $orig_longw = deg2rad($zip_row->longw);
         $orig_latn = deg2rad($zip_row->latn);

// Set the radius of the zip search can be anything
$radius = 100;

// Find all zips in a given radius
  $sql = "SELECT *, (3956 * (2 * atan2(sqrt((pow((sin(((((2*PI())/360) * 
latn) - $orig_latn)/2)),2) + cos($orig_latn) * cos((((2*PI())/360) * 
latn)) * pow((sin(((((2*PI())/360) * longw) - $orig_longw)/2)),2))), 
sqrt(1-(pow((sin(((((2*PI())/360) * latn) - $orig_latn)/2)),2) + 
cos($orig_latn) * cos((((2*PI())/360) * latn)) * 
pow((sin(((((2*PI())/360) * longw) - $orig_longw)/2)),2)))))) as 
distance FROM zips HAVING distance < $radius ORDER BY distance";

$result = $db->query($sql);

This will return all the zips within a 100 mile radius, then you can do 
whatever you need with that array. It's pretty accurate.

The Zip Code table schema the query above searches is as follows:

CREATE TABLE `zips` (
   `city` varchar(28) NOT NULL default '',
   `state` char(2) NOT NULL default '',
   `zipcode` varchar(5) NOT NULL default '',
   `Area_Code` char(3) NOT NULL default '',
   `County_FIPS` varchar(5) NOT NULL default '',
   `county` varchar(25) NOT NULL default '',
   `Timezone` varchar(5) NOT NULL default '',
   `DST` enum('Y','N') NOT NULL default 'Y',
   `latn` double NOT NULL default '0',
   `longw` double NOT NULL default '0',
   `ZipCode_Type` enum('P','U','M') default NULL,
)

Jeff




More information about the talk mailing list