Skip to content

Instantly share code, notes, and snippets.

@nickhargreaves
Last active January 27, 2016 10:30
Show Gist options
  • Save nickhargreaves/88eaff287e88c7e78857 to your computer and use it in GitHub Desktop.
Save nickhargreaves/88eaff287e88c7e78857 to your computer and use it in GitHub Desktop.
Scrapper for geocoding list with multiple location columns
<?php
/**
* Scrapper for geocoding list with multiple location columns
* If a finer location fails, it settles for the next best thing
*
* @author http://twitter.com/nickhargreaves
*/
//Db connection
$link = mysql_connect("", "", "");
mysql_select_db("", $link);
$table = '';
//geocoding boundaries, we don't want results from Neverland
$long_1 = 32;
$long_2 = 45;
$lat_1 = -5;
$lat_2 = 7;
//Google API KEY: You should have Geocoding enabled in your Google Console
$api_key = "";
//Location column names starting with the finest location
$location_columns = array('FacilityName', 'Nearest Town', 'District', 'County');
$sql = mysql_query("select * from `$table`");
while ($row = mysql_fetch_array($sql)) {
$id = $row['id'];
$geo = "0,0";
foreach ($location_columns as $column) {
if ($geo == "0,0") {
// SET ADDRESS
$address = urlencode($row[$column]);
// URL TO HTTP REQUEST
$link = "https://maps.googleapis.com/maps/api/geocode/json?address=" . $address . "&bounds=" . $lat_1 .",". $long_1 . "|" . $lat_2. "," . $long_2 ."&key=" . $api_key . "&sensor=false&oe=utf8";
// WE GET FILE CONTENT
$page = json_decode(file_get_contents($link), TRUE);
$status = $page['status'];
if ($status == "OK") {
$result = $page['results'][0];
$location = $result['geometry']['location'];
$location = $location['lat'] . "," . $location['lng'];
$geo = $location;
}
}
}
mysql_query("update $table set geo='$geo' where id='$id'");
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment