Geocoding - REST Service mit PHP nutzen

Aus Wikizone
Wechseln zu: Navigation, Suche

Beispiel aus gkk-gutachten.de

	/**
	 * get geocode lat/lon points for given address from some geocoding service
	 * thanks to Paulsen-IT <service@paulsen-it.de>
	 *
	 * @param string $address
	 * @param string $service
	 */
	private function geoGetCoords($address, $service = 'GOOGLE')
		{
		usleep(250);
		// Pre-set result
		$_result = false;
		// Do work according to chosen lookup service
		switch ($service)
			{
			// Yahoo Geocoding API
			case 'YAHOO':
				// Compose URL
				$_url = 'http://api.local.yahoo.com/MapsService/V1/geocode';
				$_url .= '?appid=' . 'MyMapApp';//$this->app_id;
				$_url .= '&location=' . urlencode($address); //rawurlencode($address);
				$curlHandle = curl_init(); // init curl

				// options
				curl_setopt($curlHandle, CURLOPT_URL, $_url); // set the url to fetch
				curl_setopt($curlHandle, CURLOPT_HEADER, 0); // set headers (0 = no headers in result)
				curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1); // type of transfer (1 = to string)
				curl_setopt($curlHandle, CURLOPT_TIMEOUT, 5); // time to wait in seconds
				curl_setopt($curlHandle, CURLOPT_CONNECTTIMEOUT, 3);

				$_result = curl_exec($curlHandle); // make the call

				curl_close($curlHandle); // close the connection
				if($_result<>'') {
				//if ($_result = file_get_contents($_url)) {
					if (preg_match('/<Latitude>(-?\d+\.\d+)<\/Latitude><Longitude>(-?\d+\.\d+)<\/Longitude>/', $_result, $_match)) {
						$_coords['lon'] = substr($_match[2],0,8);
						$_coords['lat'] = substr($_match[1],0,8);
						$_result = true;
					}
				}
				break;
			// Google Maps API
			case 'GOOGLE':
			default:
				// Compose URL
				$_url = 'http://maps.google.com/maps/api/geocode/json?sensor=false&address='.urlencode($address);
				$curlHandle = curl_init(); // init curl
				// options
				curl_setopt($curlHandle, CURLOPT_URL, $_url); // set the url to fetch
				curl_setopt($curlHandle, CURLOPT_HEADER, 0); // set headers (0 = no headers in result)
				curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1); // type of transfer (1 = to string)
				curl_setopt($curlHandle, CURLOPT_TIMEOUT, 10); // time to wait in seconds
				curl_setopt($curlHandle, CURLOPT_CONNECTTIMEOUT, 5);

				$_result = curl_exec($curlHandle); // make the call
				curl_close($curlHandle); // close the connection
				if($_result<>'') {
					$resp = json_decode($_result, true);
					if($resp['status']='OK') {
						$_coords['lon'] = substr($resp['results'][0]['geometry']['location']['lng'],0,8);
						$_coords['lat'] = substr($resp['results'][0]['geometry']['location']['lat'],0,8);
						$_result = true;
					}
				}
				break;
			}
			// Return coordinates or false
			if ($_result)
			{
				return $_coords;
			}
			return $_result;
		}