├── AUTHORS ├── LICENSE ├── README.markdown └── src ├── YahooGeocode.php ├── GoogleGeocode.php └── BaseGeocode.php /AUTHORS: -------------------------------------------------------------------------------- 1 | Original Author: 2 | * Joseph Bauser (coderjoe at coderjoe.net) 3 | 4 | Maintainers: 5 | * Joseph Bauser (coderjoe at coderjoe.net) 6 | 7 | Contributors: 8 | * Casey Eyring (casey_eyring at yahoo.com) 9 | - Bug report and fix for Google Geocode API UTF-8 error. 10 | 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License 2 | 3 | Copyright (c) 2008 Joseph Bauser (coderjoe at coderjoe.net) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.markdown: -------------------------------------------------------------------------------- 1 | Introduction 2 | ============ 3 | 4 | GoGeocode is a small set of PHP classes that were developed to simplify the process of geocoding data using both the Google and Yahoo geocoding services. 5 | 6 | While it's true that many PHP based geocoding classes exist, very few make use of the extensive data returned by the geocoding services. In many cases only the latitude and longitude coordinates are returned 7 | 8 | GoGeocode is designed to geocode a given location while preserving as much of the returned data as possible, and providing it in a PHP friendly array format. 9 | 10 | Requirements 11 | ============ 12 | * PHP 5 13 | * SimpleXML Extension 14 | 15 | Instructions 16 | ============ 17 | 18 | To use GoGeocode to geocode simply declare the GoGeocode object of your choice and use the geocode function. 19 | 20 | Example (Geocode an address using Google's geocoding service) 21 | ------------------------------------------------------------- 22 | 23 | 24 | require('GoogleGeocode.php'); 25 | 26 | $apiKey = 'your_api_key_here'; 27 | $geo = new GoogleGeocode( $apiKey ); 28 | 29 | $result = $geo->geocode( "1 Lomb Memorial Drive Rochester NY, 14623" ); 30 | 31 | print_r( $result ); 32 | 33 | Which would output: 34 | 35 | Array 36 | ( 37 | [Response] => Array 38 | ( 39 | [Status] => 200 40 | [Request] => geocode 41 | ) 42 | 43 | [Placemarks] => Array 44 | ( 45 | [0] => Array 46 | ( 47 | [Accuracy] => 8 48 | [Country] => US 49 | [AdministrativeArea] => NY 50 | [SubAdministrativeArea] => Monroe 51 | [Locality] => Rochester 52 | [Thoroughfare] => 1 Lomb Memorial Dr 53 | [PostalCode] => 14623 54 | [Latitude] => 43.092108 55 | [Longitude] => -77.675238 56 | ) 57 | 58 | ) 59 | 60 | ) 61 | 62 | *Note:* Any implementation using GoGeocode should check the status result of the geocode request to detect if any requests are being denied due to server error or rate limiting. 63 | 64 | Gotchas 65 | ======= 66 | Each geocoding API, while similar has its own subtle differences. 67 | 68 | Google, for example, always returns a HTTP status of 200, with the XML data signifying success in its node structure. Yahoo on the other hand signifies the status of the request using the HTTP status codes, indicating the type of failure or success in the data returned by the web service. 69 | 70 | In order to simplify the process GoGeocode standardizes on terminology and on operational decisions. 71 | 72 | Terminology 73 | ----------- 74 | * Response 75 | * A Response is the status and request information for a given geocode request 76 | * Placemark 77 | * A Placemark is a distinct point on a map represented by a latitude and longitude 78 | * Placemark Members 79 | * All members of a placemark follow the nomenclature set forth by the xAL or [http://www.oasis-open.org/committees/ciq/ciq.html#6 eXtensible Address Language] 80 | * Specific definitions used in GoGeocode include: country, administrative area, sub-administrative area, locality, thoroughfare, postal code, latitude, and longitude. 81 | 82 | Results 83 | ------- 84 | GoGeocode objects will always return an object regardless of request status. The returned object will contain the response's status. The service's GoGeocode object will provide a number of class constants for use in defining the geocode request's status. 85 | 86 | If the status represents success, then the object returned will contain an array of placemark data. -------------------------------------------------------------------------------- /src/YahooGeocode.php: -------------------------------------------------------------------------------- 1 | apiKey; 104 | 105 | $file = $this->loadXML( $request ); 106 | 107 | if( empty( $file ) ) { 108 | return $retVal; 109 | } 110 | 111 | $retVal['Response'] = array( 112 | 'Status' => $file['response'], 113 | 'Request' => 'geocode' 114 | ); 115 | 116 | if( $retVal['Response']['Status'] == YahooGeocode::SUCCESS ) { 117 | $xml = new SimpleXMLElement( $file['contents'] ); 118 | 119 | $xml->registerXPathNamespace('urn','urn:yahoo:maps'); 120 | 121 | $retVal['Placemarks'] = array(); 122 | if( $xml ) { 123 | $results = $xml->xpath('//urn:Result'); 124 | $countries = $xml->xpath('//urn:Country'); 125 | $adminAreas = $xml->xpath('//urn:State'); 126 | //Yahoo Geocoding has no Sub-Administrative Area (County) support. 127 | $localities = $xml->xpath('//urn:City'); 128 | $thoroughfares = $xml->xpath('//urn:Address'); 129 | $postalCodes = $xml->xpath('//urn:Zip'); 130 | $latitudes = $xml->xpath('//urn:Latitude'); 131 | $longitudes = $xml->xpath('//urn:Longitude'); 132 | 133 | if( $results ) { 134 | for( $i = 0; $i < count( $results ); $i++ ) { 135 | $attributes = $results[$i]->attributes(); 136 | 137 | $retVal['Placemarks'][$i]['Accuracy'] = (string)$attributes['precision']; 138 | $retVal['Placemarks'][$i]['Country'] = (string)$countries[$i]; 139 | 140 | if( count($adminAreas) > $i && !empty($adminAreas[$i]) ) { 141 | $retVal['Placemarks'][$i]['AdministrativeArea'] = (string) $adminAreas[$i]; 142 | } 143 | 144 | if( count($localities) > $i && !empty($localities[$i]) ) { 145 | $retVal['Placemarks'][$i]['Locality'] = (string) $localities[$i]; 146 | } 147 | 148 | if( count($thoroughfares) > $i && !empty($thoroughfares[$i]) ) { 149 | $retVal['Placemarks'][$i]['Thoroughfare'] = (string) $thoroughfares[$i]; 150 | } 151 | 152 | if( count($postalCodes) > $i && !empty($postalCodes[$i]) ) { 153 | $postalCode = explode( '-', $postalCodes[$i] ); 154 | $retVal['Placemarks'][$i]['PostalCode'] = (string) $postalCode[0]; 155 | } 156 | 157 | $retVal['Placemarks'][$i]['Latitude'] = (double)$latitudes[$i]; 158 | $retVal['Placemarks'][$i]['Longitude'] = (double)$longitudes[$i]; 159 | 160 | } 161 | } 162 | } 163 | } 164 | return $retVal; 165 | } 166 | } 167 | 168 | ?> 169 | -------------------------------------------------------------------------------- /src/GoogleGeocode.php: -------------------------------------------------------------------------------- 1 | apiKey; 141 | 142 | $nsKml = 'http://earth.google.com/kml/2.0'; 143 | $nsUrn = 'urn:oasis:names:tc:ciq:xsdschema:xAL:2.0'; 144 | 145 | $file = $this->loadXML( $url ); 146 | 147 | if( empty( $file ) ) { 148 | return $retVal; 149 | } 150 | 151 | $retVal['Response'] = array( 152 | 'Status' => (int)$file['response'], 153 | 'Request' => 'geo' 154 | ); 155 | 156 | if( $file['response'] == 200 ) { 157 | $xml = new SimpleXMLElement( $file['contents'] ); 158 | 159 | $xml->registerXPathNamespace( 'kml', $nsKml ); 160 | $xml->registerXPathNamespace( 'urn', $nsUrn ); 161 | 162 | //Now that we have the google request, and we succeeded in getting a response 163 | //from the server, lets replace oure response portion with the google response 164 | $retVal['Response']['Status'] = (int)$xml->Response->Status->code; 165 | $retVal['Response']['Request'] = (string)$xml->Response->Status->request; 166 | 167 | $retVal['Placemarks'] = array(); 168 | if( $xml && $retVal['Response']['Status'] == GoogleGeocode::SUCCESS ) 169 | { 170 | $placemarks = $xml->xpath('//kml:Placemark'); 171 | $countries = $xml->xpath('//urn:CountryNameCode'); 172 | $adminAreas = $xml->xpath('//urn:AdministrativeAreaName'); 173 | $subAdminAreas = $xml->xpath('//urn:SubAdministrativeAreaName'); 174 | $localities = $xml->xpath('//urn:LocalityName'); 175 | $thoroughfares = $xml->xpath('//urn:ThoroughfareName'); 176 | $postalCodes = $xml->xpath('//urn:PostalCodeNumber'); 177 | 178 | for( $i = 0; $i < count( $placemarks ); $i++ ) 179 | { 180 | list($longitude, $latitude) = explode( ',' , $placemarks[$i]->Point->coordinates ); 181 | $attributes = $placemarks[$i]->AddressDetails->attributes(); 182 | 183 | $retVal['Placemarks'][$i] = array(); 184 | $retVal['Placemarks'][$i]['Accuracy'] = (int)$attributes['Accuracy']; 185 | $retVal['Placemarks'][$i]['Country'] = (string)$countries[$i]; 186 | 187 | if( count( $adminAreas ) > $i ) { 188 | $retVal['Placemarks'][$i]['AdministrativeArea'] = (string)$adminAreas[$i]; 189 | } 190 | 191 | if( count( $subAdminAreas ) > $i ) { 192 | $retVal['Placemarks'][$i]['SubAdministrativeArea'] = (string)$subAdminAreas[$i]; 193 | } 194 | 195 | if( count( $localities ) > $i ) { 196 | $retVal['Placemarks'][$i]['Locality'] = (string)$localities[$i]; 197 | } 198 | 199 | if( count( $thoroughfares ) > $i ) { 200 | $retVal['Placemarks'][$i]['Thoroughfare'] = (string)$thoroughfares[$i]; 201 | } 202 | 203 | if( count( $postalCodes ) > $i ) { 204 | $retVal['Placemarks'][$i]['PostalCode'] = (string)$postalCodes[$i]; 205 | } 206 | 207 | $retVal['Placemarks'][$i]['Latitude']= (double)$latitude; 208 | $retVal['Placemarks'][$i]['Longitude'] = (double)$longitude; 209 | } 210 | } 211 | } 212 | return $retVal; 213 | } 214 | } 215 | 216 | ?> 217 | -------------------------------------------------------------------------------- /src/BaseGeocode.php: -------------------------------------------------------------------------------- 1 | setEarthRadius( 3963.1676 ); 55 | $this->setKey( $key ); 56 | } 57 | 58 | /** 59 | * Modifier for the earth mean radius 60 | * 61 | * @param float $rad The new radius of the earth to use. 62 | * @access public 63 | */ 64 | public function setEarthRadius( $rad ) { 65 | $this->earthRadius = $rad; 66 | } 67 | 68 | /** 69 | * Modifier for the API key 70 | * 71 | * @param string $key The geocoding service API key to use. 72 | * @access public 73 | */ 74 | public function setKey( $key ) { 75 | $this->apiKey = $key; 76 | } 77 | 78 | /** 79 | * Load XML from an address 80 | * 81 | * @param string $address The address representing the XML source 82 | * @access protected 83 | */ 84 | protected function loadXML( $address ) { 85 | $retVal = array(); 86 | $contents = file_get_contents( $address ); 87 | 88 | if( !empty( $http_response_header ) ) { 89 | $code = $http_response_header[0]; 90 | $matches = array(); 91 | preg_match('/^HTTP\/\d+\.\d+\s+(\d+)\s+[\w\s]+$/',$code, $matches); 92 | 93 | $retVal['response'] = $matches[1]; 94 | $retVal['contents'] = $contents; 95 | } 96 | 97 | return $retVal; 98 | } 99 | 100 | /** 101 | * Abstract function which will accept a string address 102 | * and return an array of geocoded information for the given address. 103 | * 104 | * Return types for this function are mixed based on HTTP Response Codes: 105 | * Server not found: array() 106 | * 107 | * 404: array( 'Response' => array( 108 | * 'Status' => 404, 109 | * 'Request' => the subclass specific request 110 | * ) 111 | * ); 112 | * 113 | * 200: The returned geocode information will be presented in the following format 114 | * While the example below only contains a single result, multiple results for a single 115 | * geocode request are possible and should be supported by subclasses 116 | * 117 | * array( 'Response' => array( 118 | * 'Status' => ... 119 | * 'Request' => ... 120 | * ), 121 | * 'Placemarks' => array( 122 | * array( 123 | * 'Accuracy' => ..., 124 | * 'Country' => ..., 125 | * 'AdministrativeArea' => ..., 126 | * 'SubAdministrativeArea => ..., 127 | * 'Locality' => ..., 128 | * 'Thoroughfare' => ..., 129 | * 'PostalCode' => ..., 130 | * 'Latitude' => ..., 131 | * 'Longitude' => ... 132 | * ), 133 | * array( 134 | * 'Accuracy' => ..., 135 | * 'Country' => ..., 136 | * . 137 | * . 138 | * . 139 | * ) 140 | * ) 141 | * ) 142 | * 143 | * @param string $address A string representing the address the user wants decoded. 144 | * @return array This function returns an array of geocoded location information for the given address. 145 | * @access public 146 | */ 147 | abstract public function geocode( $address ); 148 | 149 | /** 150 | * Find the distance between the two latitude and longitude coordinates 151 | * Where the latitude and longitude coordinates are in decimal degrees format. 152 | * 153 | * This function uses the haversine formula as published in the article 154 | * "Virtues of the Haversine", Sky and Telescope, vol. 68 no. 2, 1984, p. 159 155 | * 156 | * References: 157 | * http://en.wikipedia.org/w/index.php?title=Haversine_formula&oldid=176737064 158 | * http://www.movable-type.co.uk/scripts/gis-faq-5.1.html 159 | * 160 | * @param float $lat1 The first coordinate's latitude 161 | * @param float $ong1 The first coordinate's longitude 162 | * @param float $lat2 The second coordinate's latitude 163 | * @param float $long2 The second coordinate's longitude 164 | * @return float The distance between the two points in the same unit as the earth radius as set by setEarthRadius() (default miles). 165 | * @access public 166 | */ 167 | public function haversinDistance( $lat1, $long1, $lat2, $long2 ) 168 | { 169 | $lat1 = deg2rad( $lat1 ); 170 | $lat2 = deg2rad( $lat2 ); 171 | $long1 = deg2rad( $long1); 172 | $long2 = deg2rad( $long2); 173 | 174 | $dlong = $long2 - $long1; 175 | $dlat = $lat2 - $lat1; 176 | 177 | $sinlat = sin( $dlat/2 ); 178 | $sinlong = sin( $dlong/2 ); 179 | 180 | $a = ($sinlat * $sinlat) + cos( $lat1 ) * cos( $lat2 ) * ($sinlong * $sinlong); 181 | $c = 2 * asin( min( 1, sqrt( $a ) )); 182 | 183 | return $this->earthRadius * $c; 184 | } 185 | 186 | /** 187 | * Find the distance between two latitude and longitude points using the 188 | * spherical law of cosines. 189 | * 190 | * @param float $lat1 The first coordinate's latitude 191 | * @param float $ong1 The first coordinate's longitude 192 | * @param float $lat2 The second coordinate's latitude 193 | * @param float $long2 The second coordinate's longitude 194 | * @return float The distance between the two points in the same unit as the earth radius as set by setEarthRadius() (default miles). 195 | * @access public 196 | */ 197 | public function sphericalLawOfCosinesDistance( $lat1, $long1, $lat2, $long2 ) 198 | { 199 | $lat1 = deg2rad( $lat1 ); 200 | $lat2 = deg2rad( $lat2 ); 201 | $long1 = deg2rad( $long1); 202 | $long2 = deg2rad( $long2); 203 | 204 | return $this->earthRadius * acos( 205 | sin( $lat1 ) * sin( $lat2 ) + 206 | cos( $lat1 ) * cos( $lat2 ) * cos( $long2 - $long1 ) 207 | ); 208 | } 209 | 210 | /** 211 | * Find the distance between two latitude and longitude coordinates 212 | * Where the latitude and the longitude coordinates are in decimal degrees format. 213 | * 214 | * @param float $lat1 The first coordinate's latitude 215 | * @param float $ong1 The first coordinate's longitude 216 | * @param float $lat2 The second coordinate's latitude 217 | * @param float $long2 The second coordinate's longitude 218 | * @return float The distance between the two points in the same unit as the earth radius as set by setEarthRadius() (default miles). 219 | * @access public 220 | */ 221 | public function distanceBetween( $lat1, $long1, $lat2, $long2 ) 222 | { 223 | return $this->haversinDistance( $lat1, $long1, $lat2, $long2 ); 224 | } 225 | } 226 | 227 | ?> 228 | --------------------------------------------------------------------------------