/** * Call this function to find zipcodes near a certain location * @param {double} $latitude The latitude of the coordinates to search around * @param {double} $longitude The longitude of the coordinates to search around * @param {double} $miles The radius, in miles, around the central point of the zipcode * @param {double} $limit Limit on how many to return. Defaults to 100. * @return {array} Returns an array of Places_Zipcode objects, if any are found. */ public static function nearby($latitude, $longitude, $miles, $limit = 100) { // First, get a bounding box that's big enough to avoid false negatives $latGrid = $miles / 69.1703234283616; $longGrid = abs($latGrid / cos(deg2rad($latitude))); // Now, select zipcodes in a bounding box using one of the indexes $q = Places_Zipcode::select('*')->where(array('latitude >' => $latitude - $latGrid, 'latitude <' => $latitude + $latGrid)); $longitudes = array('longitude >' => max($longitude - $longGrid, -180), 'longitude <' => min($longitude + $longGrid, 180)); if ($latitude + $longGrid > 180) { $q->andWhere($longitudes, array('longitude >' => -180, 'longitude <' => $longitude + $longGrid - 180 * 2)); } else { if ($latitude - $longGrid < -180) { $q->andWhere($longitudes, array('longitude <=' => 180, 'longitude >' => $longitude - $longGrid + 180 * 2)); } else { $q->andWhere($longitudes); } } $latitude = substr($latitude, 0, 10); $longitude = substr($longitude, 0, 10); $q = $q->orderBy("POW(latitude - ({$latitude}), 2) + POW(longitude - ({$longitude}), 2)"); if ($limit) { $q = $q->limit($limit); } return $q->fetchDbRows(); }
function Places_zipcode_response() { if (Q_Request::method() !== 'GET') { return null; } $zip = array(); if (isset($_REQUEST['zipcodes'])) { $zip = $_REQUEST['zipcodes']; } else { if (isset($_REQUEST['zipcode'])) { $zip = $_REQUEST['zipcode']; } } if (is_string($zip)) { $zip = explode(',', $zip); } $zipcodes = Places_Zipcode::select('*')->where(array('zipcode' => $zip))->fetchDbRows(); Q_Response::setSlot('zipcodes', $zipcodes); }