Jump to content

grege

Members
  • Posts

    11
  • Joined

  • Last visited

Everything posted by grege

  1. Thanks for the assistance. It worked correctly. And I will look into sphinx! Appreciate the help
  2. Running into a problem... It could be a parenthesis problem I am facing, but not quite sure. Also, is there a way to retrieve that array value while in the query?? $z = implode(",", array_keys($zipArray)); sql: AND zip IN ('$z') select distinct * from pubs where id LIKE '%test%' OR title LIKE '%test%' OR city LIKE '%test%' OR state LIKE '%test%' OR zip LIKE '%test%' OR website LIKE '%test%' OR description LIKE '%test%' AND zip IN ('08002,08003,08004,08007,08009,08010,08011,08012,08016,08018,08020,08021,08022,08025,08026,08027,08028,08029,08030,08031,08032,08033,08034,08035,08036,08037,08039,08041,08042,08043,08045,08046,08048,08049,08051,08052,08053,08054,08055,08056,08057,08059,08060,08061,08062,08063,08065,08066,08068,08071,08073,08074,08075,08076,08077,08078,08080,08081,08083,08084,08085,08086,08088,08089,08090,08091,08093,08094,08095,08096,08097,08098,08099,08101,08102,08103,08104,08105,08106,08107,08108,08109,08110,08217,08310,08312,08318,08322,08326,08328,08341,08342,08343,08344,08346,08347,08350,08352,08360,08361,08362,08518,08554,08640,18966,19001,19003,19004,19006,19007,19009,19010,19012,19018,19019,19020,19021,19022,19023,19025,19026,19027,19029,19030,19031,19032,19033,19034,19035,19036,19038,19040,19041,19043,19046,19047,19050,19053,19054,19055,19056,19057,19064,19066,19070,19072,19074,19075,19076,19078,19079,19082,19083,19090,19092,19093,19095,19096,19098,19099,19101,19102,19103,19104,19105,19106,19107,19108,19109,19110,19111,19112,19113,19114,19115,19116,19118,19119,19120,19121,19122,19123,19124,19125,19126,19127,19128,19129,19130,19131,19132,19133,19134,19135,19136,19137,19138,19139,19140,19141,19142,19143,19144,19145,19146,19147,19148,19149,19150,19151,19152,19153,19154,19155,19160,19161,19162,19170,19171,19172,19173,19175,19176,19177,19178,19179,19181,19182,19183,19184,19185,19187,19188,19191,19192,19193,19194,19195,19196,19197,19244,19255,19428,19444,19462') order by title
  3. Exactly what I am looking for I think. Gonna try it out now! Thanks so much neil, such quick responses.
  4. Thanks for the response. Is it possible to implement that into the sql query tho? So that I will then only take results where table.zip = *Any array key in $arr* and then retrieve the distance
  5. Hey Guys, I need some assistance, hopefully there is just a simple command that I am not aware of or an easy answer to this. Suppose I have an array with x amount of values... $arr = array("111111" => 10, "222222" => 20); And i have a query.. mysql_query("SELECT * FROM table WHERE table.zip = "111111" "); Suppose I want to modify the query, so it can check if table.zip exists anywhere in $arr, regardless of length of array. And Select the value that the array location refers to. So I need it to check if "111111" is anywhere in the array, and then take the value 10. The example I am applying this to is that I have a database full of business addresses/zip codes and a database full of every zip code in country. So I have a script to get every zip within x miles, and the distance from it, but need to be able to apply it when I query my business addresses to see if it exists within x miles. Thanks! Greg
  6. Hey Guys, So I have a zip code database with 40,000 some entries... and I am reading a query and returning it and need it to store it in array similar to this snippet of code . $cities = array( array('city'=>'New York', 'state'=>'NY', 'zip'=>'10001'), array('city'=>'Los Angeles', 'state'=>'CA', 'zip'=>'90001'), array('city'=>'Chicago', 'state'=>'IL', 'zip'=>'60601'), array('city'=>'Houston', 'state'=>'TX', 'zip'=>'77001'), array('city'=>'Phoenix', 'state'=>'AZ', 'zip'=>'85001'), array('city'=>'Philadelphia', 'state'=>'PA', 'zip'=>'19019'), array('city'=>'San Antonio', 'state'=>'TX', 'zip'=>'78201'), array('city'=>'Dallas', 'state'=>'TX', 'zip'=>'75201'), array('city'=>'San Diego', 'state'=>'CA', 'zip'=>'92101'), array('city'=>'San Jose', 'state'=>'CA', 'zip'=>'95101'), array('city'=>'Detroit', 'state'=>'MI', 'zip'=>'48201'), array('city'=>'San Francisco', 'state'=>'CA', 'zip'=>'94101'), array('city'=>'Jacksonville', 'state'=>'FL', 'zip'=>'32099'), array('city'=>'Indianapolis', 'state'=>'IN', 'zip'=>'46201'), array('city'=>'Austin', 'state'=>'TX', 'zip'=>'73301'), array('city'=>'Columbus', 'state'=>'OH', 'zip'=>'43085'), array('city'=>'Fort Worth', 'state'=>'TX', 'zip'=>'76101'), array('city'=>'Charlotte', 'state'=>'NC', 'zip'=>'28201'), array('city'=>'Memphis', 'state'=>'TN', 'zip'=>'37501'), array('city'=>'Baltimore', 'state'=>'MD', 'zip'=>'21201'), ); Here is the code I currently have... But it is not being stored into an array, it is just a mysqli_result object with the correct amount of num_rows, and fields. $cities = $zip->getAllZipCityState(); function getAllZipCityState() { // Get ALL Zip / City / State $query = 'SELECT ' . $this->dbZip . ', ' . $this->dbCity . ', ' . $this->dbState . ' '; $query.= 'FROM ' . $this->dbTable . ' '; //$qry = mysql_query($query,$this->db); $qry = $this->db->query($query); if(!$qry){ echo "MySql Error #".mysqli_errno($this->db).': '.mysqli_error($this->db).'<br>'; die; } //return mysqli_fetch_array($qry); return $qry; } Thanks!
  7. Problem Resolved... <?php /** * Class to find zip codes within an approximate * distance of another zip code. This can be useful * when trying to find retailers within a certain * number of miles to a customer. * * This class makes some assumptions that I consider * pretty safe. First it assumes there is a database * that houses all of the zip code information. * Secondly it assumes there is a way to validate a * zip code for a given country. It makes one bad * assumption and that is that the world is flat. See * comments below for an explanation. * * @author Scott Mattocks * @created 2004-05-03 * @updated 2004-05-14 * @updated 2006-05-22 - MySQL Conversion by Allan Bogh * - Added precisionDistance() function to make calculations * more accurate (within 2 miles). * - Modified class initialization to make custom database settings * more effective. * New initialization steps: * $zip = new ZipCodesRange($appconf['dbconnection'],'98303',50); * $zip->setTableName('zip_codes'); //optional * $zip->setZipColumn('zip'); //optional * $zip->setLonColumn('longitude'); //optional * $zip->setLatColumn('latitude'); //optional * $zip->setZipCodesInRange(); //call to initialize zip array * echo '<pre>'; * print_r($zip->getZipCodesInRange()); * echo '</pre>'; */ class ZipCodesRange { /** * The conversion factor to go from miles to degrees. * @var float */ var $milesToDegrees = .01445; /** * The zipcode we are starting from. * @var string */ var $zipCode; /** * The maximum distance in miles to return results for. * @var float */ var $range; /** * The country the zip code is in. * @var string Two character ISO code. */ var $country; /** * The result of our search. * array(zip1 => distance, zip2 =>distance,...) * @var array */ var $zipCodes = array (); /** * The database table to look for zipcodes in. * @var string */ var $dbTable = 'zips'; /** * The name of the column containing the zip code. * @var string */ var $dbZip = 'zip'; /** * The name of the column containing the longitude. * @var string */ var $dbLon = 'lon'; /** * The name of the column containing the latitude. * @var string */ var $dbLat = 'lat'; var $db; /** * Constructor. Calls initialization method. * * @access private * @param resource $db The link identifier for the database. * @param string $zipCode * @param float $range * @param string $country Optional. Defaults to US. * @return object */ function ZipCodesRange($db, $zipCode, $range, $country = 'US') { $this->_initialize($db, $zipCode, $range, $country); } /** * Initialization method. * Checks data and sets member variables. * * @access private * @param resource $db The link identifier for the database. * @param string $zipCode * @param float $range * @param string $country Optional. Defaults to US. * @return boolean */ function _initialize($db, $zipCode, $range, $country) { //set up the database connection $this->db = $db; // Check the country. if ($this->validateCountry($country)) { $this->country = $country; } else { trigger_error('Invalid country: ' . $country); return FALSE; } // Check the zipcode. if ($this->validateZipCode($zipCode, $country)) { $this->zipCode = $zipCode; } else { trigger_error('Invalid zip code: ' . $zipCode); return FALSE; } // We don't need a special method to check the range. if (is_numeric($range) && $range >= 0) { $this->range = $range; } else { trigger_error('Invalid range: ' . $range); return FALSE; } // Set up the zip codes. //return $this->setZipCodesInRange(); } /** * Get all of the zip codes from the database. * Currently this method is called on construction but * it doesn't have to be. * * @access public * @return boolean */ function setZipCodesInRange() { // First check that everything is set. if (!isset($this->zipCode) || !isset($this->range) || !isset($this->country)) { trigger_error('Cannot get zip codes. Class not initialized properly.'); return FALSE; } // Get the max longitude and latitude of the starting point. $maxCoords = $this->getRangeBox(); // The query. $query = 'SELECT ' . $this->dbZip . ', ' . $this->dbLat . ', '; $query.= $this->dbLon . ' '; $query.= 'FROM ' . $this->dbTable . ' '; $query.= ' WHERE '; $query.= ' (' . $this->dbLat . ' <= ' . $maxCoords['max_lat'] . ' '; $query.= ' AND '; $query.= ' ' . $this->dbLat . ' >= ' . $maxCoords['min_lat'] . ') '; $query.= ' AND '; $query.= ' (' . $this->dbLon . ' <= ' . $maxCoords['max_lon'] . ' '; $query.= ' AND '; $query.= ' ' . $this->dbLon . ' >= ' . $maxCoords['min_lon'] . ') '; // Query the database. //$qry = mysql_query($query,$this->db); $qry = $this->db->query($query); // Check for errors. if (!$qry) { //trigger_error('MySQL Error #'.mysql_errno($this->db).': '.mysql_error($this->db), E_USER_ERROR); } // Process each row. //while ($result = mysql_fetch_array($qry)) { while ($result = mysqli_fetch_array($qry)) { // Get the distance form the origin (imperfect see below). $distance = $this->precisionDistance($result[$this->dbLat], $result[$this->dbLon]); // Double check that the distance is within the range. if ($distance < $this->range) { // Add the zip to the array $this->zipCodes[$result[$this->dbZip]] = $distance; } } return TRUE; } /** * Return the array of results. * * @access public * @param none * @return &array */ function &getZipCodesInRange() { return $this->zipCodes; } /** * Calculate the distance from the coordinates are from the * origin zip code. * * The method is quite imperfect. It assumes as flat Earth. * The values are quite accurate (depending on the conversion * factor used) for zip codes close to the equator. I found * some crazy formula for calulating distance on a sphere * but I am not good enough at calculus to convert that into * working code. * * @access public * @param float $lat The latitude you want to know the distance to. * @param float $lon The longitude you want to know the distance to. * @param float $zip The zip code you want to know the distance from. * @param int $percision The number of decimals places in the distance. * @return float The distance from the zip code to the coordinates. */ function calculateDistance($lat, $lon, $zip = NULL, $percision = 2) { // Check the zip first. if (!isset ($zip)) { // Make it default to the origin zip code. // Could be used to calculate distances from other points. $zip = $this->zipCode; } // Get the coordinates of our starting zip code. list ($starting_lon, $starting_lat) = $this->getLonLat($zip); // Get the difference in miles for both coordinates. $diffLonMiles = ($starting_lon - $lon) / $this->milesToDegrees; $diffLatMiles = ($starting_lat - $lat) / $this->milesToDegrees; // Calculate the distance between two points. $distance = sqrt(($diffLonMiles * $diffLonMiles) + ($diffLatMiles * $diffLatMiles)); // Return the distance rounded to the defined percision. return round($distance, $percision); } /** * See the report for calculateDistance function. */ function precisionDistance($lat, $lon, $zip = NULL, $precision = 2){ $earthsradius = 3963.19; // Check the zip first. if (!isset ($zip)) { // Make it default to the origin zip code. // Could be used to calculate distances from other points. $zip = $this->zipCode; } // Get the coordinates of our starting zip code. list ($starting_lon, $starting_lat) = $this->getLonLat($zip); $pi = pi(); $c = sin($starting_lat/(180/$pi)) * sin($lat/(180/$pi)) + cos($starting_lat/(180/$pi)) * cos($lat/(180/$pi)) * cos($lon/(180/$pi) - $starting_lon/(180/$pi)); $distance = $earthsradius * acos($c); return round($distance,$precision); } /** * Get the longitude and latitude for a single zip code. * * @access public * @param string $zip The zipcode to get the coordinates for. * @return array Numerically index with longitude first. */ function getLonLat($zip) { // Get the longitude and latitude for the zip code. $query = 'SELECT ' . $this->dbLon . ', ' . $this->dbLat . ' '; $query.= 'FROM ' . $this->dbTable . ' '; $query.= 'WHERE ' . $this->dbZip . ' = \'' . addslashes($zip) . '\' '; //$qry = mysql_query($query,$this->db); $qry = $this->db->query($query); if(!$qry){ //echo "MySql Error #".mysql_errno($this->db).': '.mysql_error($this->db).'<br>'; die; } return mysqli_fetch_array($qry); } /** * Check to see if the country is valid. * * Not implemented in any useful manner. * * @access public * @param string $country The country to check. * @return boolean */ function validateCountry($country) { return (strlen($country) == 2); } /** * Check to see if a zip code is valid. * * Not implemented in any useful manner. * * @access public * @param string $zip The code to validate. * @param string $country The country the zip code is in. * @return boolean */ function validateZipCode($zip, $country = NULL) { // Set the country if we need to. if (!isset($country)) { $country = $this->country; } // There should be a way to check the zip code for every // acceptabe country. return TRUE; } /** * Get the maximum and minimum longitude and latitude values * that our zip codes can be in. * * Not all zipcodes in this box will be with in the range. * The closest edge of this box is exactly range miles away * from the origin but the corners are sqrt(2(range^2)) miles * away. That is why we have to double check the ranges. * * @access public * @param none * @return &array The edges of the box. */ function &getRangeBox() { // Calculate the degree range using the mile range $degrees = $this->range * $this->milesToDegrees; // Get the coords for our starting zip code. list($starting_lon, $starting_lat) = $this->getLonLat($this->zipCode); // Set up an array to return. $ret_array = array (); // Lat/Lon ranges $ret_array['max_lat'] = $starting_lat + $degrees; $ret_array['max_lon'] = $starting_lon + $degrees; $ret_array['min_lat'] = $starting_lat - $degrees; $ret_array['min_lon'] = $starting_lon - $degrees; return $ret_array; } /** * Allow users to set the name of the database table holding * the information. * * @access public * @param string $table The name of the db table. * @return void */ function setTableName($table) { $this->dbTable = $table; } /** * Allow users to set the name of the column holding the * latitude value. * * @access public * @param string $lat The name of the column. * @return void */ function setLatColumn($lat) { $this->dbLat = $lat; } /** * Allow users to set the name of the column holding the * longitude value. * * @access public * @param string $lon The name of the column. * @return void */ function setLonColumn($lon) { $this->dbLon = $lon; } /** * Allow users to set the name of the column holding the * zip code value. * * @access public * @param string $zips The name of the column. * @return void */ function setZipColumn($zip) { $this->dbZip = $zip; } /** * Set a new origin and re-get the data. * * @access public * @param string $zip The new origin. * @return void */ function setNewOrigin($zip) { if ($this->validateZipCode($zip)) { $this->zipCode = $zip; $this->setZipCodesInRange(); } } /** * Set a new range and re-get the data. * * @access public * @param float $range The new range. * @return void */ function setNewRange($range) { if (is_numeric($range)) { $this->range = $range; $this->setZipCodesInRange(); } } /** * Set a new country but don't re-get the data. * * It isn't any good to check a zip code in two * countries cause the rules for zip codes vary from * country to country. * * @access public * @param string $country The new country. * @return void */ function setNewCountry($coutry) { if ($this->validateCountry($country)) { $this->country = $country; } } /** * Allow users to set the converstion ratio. * Hopefully you are changing the percision * and not setting a bad value. * * @access public * @param float $rate The new value. * @return void */ function setConversionRate($rate) { if (is_numeric($rate)) { $this->milesToDegrees = $rate; } } } /* Debugging lines $zcr = new ZipCodesRange(10965, 10); print_r($zcr); */ ?>
  8. @rifts not quite sure what your referring to with this.
  9. Yes, I understand I have a majority of my scripts written using the mysqli_ commands, and the zip codes class has mysql_errno mysql_query & mysql_error. Is it as simple as modifying the ZipCodesRange.class.php to use mysqli?? Following two snippets in the ZipCodesRange.class.php with mysql_ commands // Query the database. $qry = mysql_query($query,$this->db); // Check for errors. if (!$qry) { trigger_error('MySQL Error #'.mysql_errno($this->db).': '.mysql_error($this->db), E_USER_ERROR); } // Process each row. while ($result = mysql_fetch_array($qry)) { // Get the distance form the origin (imperfect see below). $distance = $this->precisionDistance($result[$this->dbLat], $result[$this->dbLon]); // Double check that the distance is within the range. if ($distance < $this->range) { // Add the zip to the array $this->zipCodes[$result[$this->dbZip]] = $distance; } } return TRUE; } function getLonLat($zip) { // Get the longitude and latitude for the zip code. $query = 'SELECT ' . $this->dbLon . ', ' . $this->dbLat . ' '; $query.= 'FROM ' . $this->dbTable . ' '; $query.= 'WHERE ' . $this->dbZip . ' = \'' . addslashes($zip) . '\' '; $qry = mysql_query($query,$this->db); if(!$qry){ echo "MySql Error #".mysql_errno($this->db).': '.mysql_error($this->db).'<br>'; die; } return mysql_fetch_array($qry); }
  10. Hey Guys, So I am working on implementing zip codes to my database. I found a zip code calculator script, and I am forced to pass the database connection to the class. Although, I realize I use a mysqli connection and the zipcodes class uses mysql... Appreciate if anyone could assist me in solving my issue. THANKS! ERRORS... zip.php <?php require_once("class/mysql_connect.php"); $mysql = New MySQL(); require_once("ZipCodesRange.class.php"); //initialization, pass in DB connection, from zip code, distance in miles. $zip = new ZipCodesRange($mysql,'98303',50); //configuration $zip->setTableName('zipcodes'); //optional, default is zips. $zip->setZipColumn('ZipCode'); //optional, default is zip. $zip->setLonColumn('Longitude'); //optional, default is lon. $zip->setLatColumn('Latitude'); //optional, default is lat. //do the work $zip->setZipCodesInRange(); //call to initialize zip array //zip code output, other processing can be done from this array. $zipArray = $zip->getZipCodesInRange(); echo '<pre>'; print_r($zipArray); echo '</pre>'; ?> mysql_connect.php <?php require_once ("includes/constants.php"); class MySQL { private $conn; /** * MySQL::__construct() * * @return */ function __construct() { $this->conn = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME) or die("Problem connecting to database"); $dbc = $this->conn; } /* * Query the database * Example: $result = $mysql->query($q); */ /** * MySQL::query() * * @param mixed $q * @return */ function query($q) { return $this->conn->query($q); } ...CONTINUED ZipCodesRange.class.php <?php /** * Class to find zip codes within an approximate * distance of another zip code. This can be useful * when trying to find retailers within a certain * number of miles to a customer. * * This class makes some assumptions that I consider * pretty safe. First it assumes there is a database * that houses all of the zip code information. * Secondly it assumes there is a way to validate a * zip code for a given country. It makes one bad * assumption and that is that the world is flat. See * comments below for an explanation. * * @author Scott Mattocks * @created 2004-05-03 * @updated 2004-05-14 * @updated 2006-05-22 - MySQL Conversion by Allan Bogh * - Added precisionDistance() function to make calculations * more accurate (within 2 miles). * - Modified class initialization to make custom database settings * more effective. * New initialization steps: * $zip = new ZipCodesRange($appconf['dbconnection'],'98303',50); * $zip->setTableName('zip_codes'); //optional * $zip->setZipColumn('zip'); //optional * $zip->setLonColumn('longitude'); //optional * $zip->setLatColumn('latitude'); //optional * $zip->setZipCodesInRange(); //call to initialize zip array * echo '<pre>'; * print_r($zip->getZipCodesInRange()); * echo '</pre>'; */ class ZipCodesRange { /** * The conversion factor to go from miles to degrees. * @var float */ var $milesToDegrees = .01445; /** * The zipcode we are starting from. * @var string */ var $zipCode; /** * The maximum distance in miles to return results for. * @var float */ var $range; /** * The country the zip code is in. * @var string Two character ISO code. */ var $country; /** * The result of our search. * array(zip1 => distance, zip2 =>distance,...) * @var array */ var $zipCodes = array (); /** * The database table to look for zipcodes in. * @var string */ var $dbTable = 'zips'; /** * The name of the column containing the zip code. * @var string */ var $dbZip = 'zip'; /** * The name of the column containing the longitude. * @var string */ var $dbLon = 'lon'; /** * The name of the column containing the latitude. * @var string */ var $dbLat = 'lat'; var $db; /** * Constructor. Calls initialization method. * * @access private * @param resource $db The link identifier for the database. * @param string $zipCode * @param float $range * @param string $country Optional. Defaults to US. * @return object */ function ZipCodesRange($db, $zipCode, $range, $country = 'US') { $this->_initialize($db, $zipCode, $range, $country); } /** * Initialization method. * Checks data and sets member variables. * * @access private * @param resource $db The link identifier for the database. * @param string $zipCode * @param float $range * @param string $country Optional. Defaults to US. * @return boolean */ function _initialize($db, $zipCode, $range, $country) { //set up the database connection $this->db = $db; // Check the country. if ($this->validateCountry($country)) { $this->country = $country; } else { trigger_error('Invalid country: ' . $country); return FALSE; } // Check the zipcode. if ($this->validateZipCode($zipCode, $country)) { $this->zipCode = $zipCode; } else { trigger_error('Invalid zip code: ' . $zipCode); return FALSE; } // We don't need a special method to check the range. if (is_numeric($range) && $range >= 0) { $this->range = $range; } else { trigger_error('Invalid range: ' . $range); return FALSE; } // Set up the zip codes. //return $this->setZipCodesInRange(); } /** * Get all of the zip codes from the database. * Currently this method is called on construction but * it doesn't have to be. * * @access public * @return boolean */ function setZipCodesInRange() { // First check that everything is set. if (!isset($this->zipCode) || !isset($this->range) || !isset($this->country)) { trigger_error('Cannot get zip codes. Class not initialized properly.'); return FALSE; } // Get the max longitude and latitude of the starting point. $maxCoords = $this->getRangeBox(); // The query. $query = 'SELECT ' . $this->dbZip . ', ' . $this->dbLat . ', '; $query.= $this->dbLon . ' '; $query.= 'FROM ' . $this->dbTable . ' '; $query.= ' WHERE '; $query.= ' (' . $this->dbLat . ' <= ' . $maxCoords['max_lat'] . ' '; $query.= ' AND '; $query.= ' ' . $this->dbLat . ' >= ' . $maxCoords['min_lat'] . ') '; $query.= ' AND '; $query.= ' (' . $this->dbLon . ' <= ' . $maxCoords['max_lon'] . ' '; $query.= ' AND '; $query.= ' ' . $this->dbLon . ' >= ' . $maxCoords['min_lon'] . ') '; // Query the database. $qry = mysql_query($query,$this->db); // Check for errors. if (!$qry) { trigger_error('MySQL Error #'.mysql_errno($this->db).': '.mysql_error($this->db), E_USER_ERROR); } // Process each row. while ($result = mysql_fetch_array($qry)) { // Get the distance form the origin (imperfect see below). $distance = $this->precisionDistance($result[$this->dbLat], $result[$this->dbLon]); // Double check that the distance is within the range. if ($distance < $this->range) { // Add the zip to the array $this->zipCodes[$result[$this->dbZip]] = $distance; } } return TRUE; } /** * Return the array of results. * * @access public * @param none * @return &array */ function &getZipCodesInRange() { return $this->zipCodes; } /** * Calculate the distance from the coordinates are from the * origin zip code. * * The method is quite imperfect. It assumes as flat Earth. * The values are quite accurate (depending on the conversion * factor used) for zip codes close to the equator. I found * some crazy formula for calulating distance on a sphere * but I am not good enough at calculus to convert that into * working code. * * @access public * @param float $lat The latitude you want to know the distance to. * @param float $lon The longitude you want to know the distance to. * @param float $zip The zip code you want to know the distance from. * @param int $percision The number of decimals places in the distance. * @return float The distance from the zip code to the coordinates. */ function calculateDistance($lat, $lon, $zip = NULL, $percision = 2) { // Check the zip first. if (!isset ($zip)) { // Make it default to the origin zip code. // Could be used to calculate distances from other points. $zip = $this->zipCode; } // Get the coordinates of our starting zip code. list ($starting_lon, $starting_lat) = $this->getLonLat($zip); // Get the difference in miles for both coordinates. $diffLonMiles = ($starting_lon - $lon) / $this->milesToDegrees; $diffLatMiles = ($starting_lat - $lat) / $this->milesToDegrees; // Calculate the distance between two points. $distance = sqrt(($diffLonMiles * $diffLonMiles) + ($diffLatMiles * $diffLatMiles)); // Return the distance rounded to the defined percision. return round($distance, $percision); } /** * See the report for calculateDistance function. */ function precisionDistance($lat, $lon, $zip = NULL, $precision = 2){ $earthsradius = 3963.19; // Check the zip first. if (!isset ($zip)) { // Make it default to the origin zip code. // Could be used to calculate distances from other points. $zip = $this->zipCode; } // Get the coordinates of our starting zip code. list ($starting_lon, $starting_lat) = $this->getLonLat($zip); $pi = pi(); $c = sin($starting_lat/(180/$pi)) * sin($lat/(180/$pi)) + cos($starting_lat/(180/$pi)) * cos($lat/(180/$pi)) * cos($lon/(180/$pi) - $starting_lon/(180/$pi)); $distance = $earthsradius * acos($c); return round($distance,$precision); } /** * Get the longitude and latitude for a single zip code. * * @access public * @param string $zip The zipcode to get the coordinates for. * @return array Numerically index with longitude first. */ function getLonLat($zip) { // Get the longitude and latitude for the zip code. $query = 'SELECT ' . $this->dbLon . ', ' . $this->dbLat . ' '; $query.= 'FROM ' . $this->dbTable . ' '; $query.= 'WHERE ' . $this->dbZip . ' = \'' . addslashes($zip) . '\' '; $qry = mysql_query($query,$this->db); if(!$qry){ echo "MySql Error #".mysql_errno($this->db).': '.mysql_error($this->db).'<br>'; die; } return mysql_fetch_array($qry); } /** * Check to see if the country is valid. * * Not implemented in any useful manner. * * @access public * @param string $country The country to check. * @return boolean */ function validateCountry($country) { return (strlen($country) == 2); } /** * Check to see if a zip code is valid. * * Not implemented in any useful manner. * * @access public * @param string $zip The code to validate. * @param string $country The country the zip code is in. * @return boolean */ function validateZipCode($zip, $country = NULL) { // Set the country if we need to. if (!isset($country)) { $country = $this->country; } // There should be a way to check the zip code for every // acceptabe country. return TRUE; } /** * Get the maximum and minimum longitude and latitude values * that our zip codes can be in. * * Not all zipcodes in this box will be with in the range. * The closest edge of this box is exactly range miles away * from the origin but the corners are sqrt(2(range^2)) miles * away. That is why we have to double check the ranges. * * @access public * @param none * @return &array The edges of the box. */ function &getRangeBox() { // Calculate the degree range using the mile range $degrees = $this->range * $this->milesToDegrees; // Get the coords for our starting zip code. list($starting_lon, $starting_lat) = $this->getLonLat($this->zipCode); // Set up an array to return. $ret_array = array (); // Lat/Lon ranges $ret_array['max_lat'] = $starting_lat + $degrees; $ret_array['max_lon'] = $starting_lon + $degrees; $ret_array['min_lat'] = $starting_lat - $degrees; $ret_array['min_lon'] = $starting_lon - $degrees; return $ret_array; } /** * Allow users to set the name of the database table holding * the information. * * @access public * @param string $table The name of the db table. * @return void */ function setTableName($table) { $this->dbTable = $table; } /** * Allow users to set the name of the column holding the * latitude value. * * @access public * @param string $lat The name of the column. * @return void */ function setLatColumn($lat) { $this->dbLat = $lat; } /** * Allow users to set the name of the column holding the * longitude value. * * @access public * @param string $lon The name of the column. * @return void */ function setLonColumn($lon) { $this->dbLon = $lon; } /** * Allow users to set the name of the column holding the * zip code value. * * @access public * @param string $zips The name of the column. * @return void */ function setZipColumn($zip) { $this->dbZip = $zip; } /** * Set a new origin and re-get the data. * * @access public * @param string $zip The new origin. * @return void */ function setNewOrigin($zip) { if ($this->validateZipCode($zip)) { $this->zipCode = $zip; $this->setZipCodesInRange(); } } /** * Set a new range and re-get the data. * * @access public * @param float $range The new range. * @return void */ function setNewRange($range) { if (is_numeric($range)) { $this->range = $range; $this->setZipCodesInRange(); } } /** * Set a new country but don't re-get the data. * * It isn't any good to check a zip code in two * countries cause the rules for zip codes vary from * country to country. * * @access public * @param string $country The new country. * @return void */ function setNewCountry($coutry) { if ($this->validateCountry($country)) { $this->country = $country; } } /** * Allow users to set the converstion ratio. * Hopefully you are changing the percision * and not setting a bad value. * * @access public * @param float $rate The new value. * @return void */ function setConversionRate($rate) { if (is_numeric($rate)) { $this->milesToDegrees = $rate; } } } /* Debugging lines $zcr = new ZipCodesRange(10965, 10); print_r($zcr); */ ?>
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.