Google Geocoding API with PHP


Понадобилось обработать список из 1500 адресов вида: штат, город, зип. Необходимо было еще получить координты. Помог следующий скрипт:

geocoding.php

<?php

set_time_limit(0);

function lookup($string){
	$orig = trim($string);
   $string = str_replace (" ", "+", urlencode($string));
   $details_url = "http://maps.googleapis.com/maps/api/geocode/json?address=".$string."&sensor=false";
 
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $details_url);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   $response = json_decode(curl_exec($ch), true);
 
   // If Status Code is ZERO_RESULTS, OVER_QUERY_LIMIT, REQUEST_DENIED or INVALID_REQUEST
   if ($response['status'] != 'OK') {
    return null;
   }
 
   // print_r($response);
   $geometry = $response['results'][0]['geometry'];
 
    $longitude = $geometry['location']['lat'];
    $latitude = $geometry['location']['lng'];
 
    $array = array(
        'latitude' => $geometry['location']['lat'],
        'longitude' => $geometry['location']['lng'],
        'location_type' => $geometry['location_type'],
    );
	$st = $orig.",".$geometry['location']['lat'].",".$geometry['location']['lng'];
 
    return $st;
 
}

if ( $_POST['addr']) {
	$addr = "";
	$descr_array = explode( "\n", $_POST['addr']);
	for ( $i = 0; $i < count( $descr_array); $i ++) {
		$addr.=lookup($descr_array[$i])."\n";
		file_put_contents("base.txt",$addr);
	}
	// echo $addr;
}

?>

<form action='<?=$PHP_SELF?>' method='post'>
	<textarea name="addr" id="addr"></textarea>
	<button type="submit">Submit</button>
</form>