<?php
set_time_limit(0);
require('db_login.php');
$db=mysql_connect($host, $username, $password) or die('Database connection failed: '.mysql_error());
mysql_select_db($db_name, $db) or die('Database selection failed: '.mysql_error());
$query_delay=1500000;
$query_count=0;
$table_names=array('your_table_name_here');
$length=count($table_names);
for($i=0; $i<$length; $i++){
$mysql_query="SELECT id, ADDRESS_1, ADDRESS_2, POST_TOWN, COUNTY, POST_CODE from {$table_names[$i]} WHERE lat=0 AND lng=0";
$mysql_result=mysql_query($mysql_query) or die('Database query failed: '.mysql_error());
while(list($id, $address1, $address2, $post_town, $count, $postcode)=mysql_fetch_row($mysql_result)){
$geocode_query='http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address='.rawurlencode($address1).'+'.rawurlencode($address2).'+'.rawurlencode($post_town).'+'.rawurlencode($county).'+'.rawurlencode($postcode);
$geocode_result=file_get_contents($geocode_query);
$query_count++;
$geocode_json=json_decode($geocode_result, true);
/* uncomment to debug any errors
switch(json_last_error()){
case JSON_ERROR_DEPTH:
echo 'Maximum stack depth exceeded';
break;
case JSON_ERROR_CTRL_CHAR:
echo 'Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo 'Syntax error, malformed JSON';
break;
case JSON_ERROR_NONE:
echo 'No errors';
break;
} */
/* echo '<br><pre>';
print_r($geocode_json);
echo '</pre><br>'; */
if($geocode_json['status']=='OK'){
$lat=$geocode_json['results'][0]['geometry']['location']['lat'];
$lng=$geocode_json['results'][0]['geometry']['location']['lng'];
} else {
// these values will be used if the geocode fails
$lat=360;
$lng=360;
}
$update_query="UPDATE {$table_names[$i]} SET lat=$lat, lng=$lng WHERE id=$id LIMIT 1";
$update_result=mysql_query($update_query) or die('Database update failed: '.mysql_error());
if($geocode_json['status']=='OVER_QUERY_LIMIT'){
$query_delay+=1500000;
}
if($query_count>2500){
die("Exiting. Query count: $query_count");
}
usleep($query_delay);
}
echo "Complete. Query count: $query_count";
}
?>