Created
April 26, 2011 19:41
-
-
Save mheadd/942959 to your computer and use it in GitHub Desktop.
Simple PHP class that can be used to fetch locations from PHLAPI.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * | |
| * A simple class to retrieve point data from PHLAPI. | |
| * | |
| */ | |
| class PhlApi { | |
| // Private class members. | |
| private $host; | |
| private $port; | |
| private $data_set; | |
| private $version; | |
| private $bbox; | |
| // Class constructor. | |
| public function __construct($host, $port, $data_set, $version="v1") { | |
| $this->host = $host; | |
| $this->port = $port; | |
| $this->data_set = $data_set; | |
| $this->version = $version; | |
| } | |
| // Gets locations based on bounding box coordinates. | |
| public function getLocations($lat1, $lon1, $lat2, $lon2) { | |
| $this->bbox = self::makeBoundingBox($lat1, $lon1, $lat2, $lon2); | |
| return self::makeApiCall(); | |
| } | |
| // Make HTTP request to PHLAPI. | |
| private function makeApiCall() { | |
| $url = 'http://'. $this->host . ':' . $this->port . '/' . $this->version .'/' . $this->data_set . '?bbox=' . $this->bbox; | |
| $ch = curl_init($url); | |
| curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
| curl_setopt($ch, CURLOPT_HTTPHEADER, array("Host: $this->host:$this->port")); | |
| $result = curl_exec($ch); | |
| $error = curl_errno($ch); | |
| $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); | |
| if($code != '200') { | |
| throw new PhlApiException("Invalid response code returned: " . $code); | |
| } | |
| elseif($result === false) { | |
| throw new PhlApiException("An error occured: " . $error); | |
| } | |
| else { | |
| return $result; | |
| } | |
| } | |
| // Utility function to construct bounding box | |
| private function makeBoundingBox($lat1, $lon1, $lat2, $lon2) { | |
| return $this->bbox = implode(",", array($lat1, $lon1, $lat2, $lon2)); | |
| } | |
| } | |
| /** | |
| * | |
| * Class to wrap exceptions. | |
| * | |
| */ | |
| class PhlApiException extends Exception { } | |
| try { | |
| // Create a new instance of PhlApi clas. | |
| $phlapi = new PhlApi("phlapi.com", 5984, "phl_libraries"); | |
| // Pass in bounding box coordinates. | |
| $libraries = $phlapi->getLocations("-75.1733961","39.9438813","-75.1433961","39.9738813"); | |
| // Get JSON response from PHLAPI. | |
| $locations = json_decode($libraries); | |
| // Iterate over result JSON and write out library names. | |
| foreach($locations->features as $location) { | |
| echo "Branch name: ". $location->properties->properties->BRANCH_NAM ."\n"; | |
| } | |
| } | |
| catch (PhlApiException $ex) { | |
| die($ex->getMessage()); | |
| } | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment