Skip to content

Commit

Permalink
Merge pull request #100 from lolandese/zero-results-googlegeocode
Browse files Browse the repository at this point in the history
Return an empty value if Google API returns zero results instead of throwing a fatal error.
  • Loading branch information
phayes committed Jun 29, 2015
2 parents 3e37b19 + 54bce1f commit 9e9dd12
Showing 1 changed file with 15 additions and 7 deletions.
22 changes: 15 additions & 7 deletions lib/adapters/GoogleGeocode.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class GoogleGeocode extends GeoAdapter
*/
public function read($address, $return_type = 'point', $bounds = FALSE, $return_multiple = FALSE) {
if (is_array($address)) $address = join(',', $address);

if (gettype($bounds) == 'object') {
$bounds = $bounds->getBBox();
}
Expand All @@ -41,13 +41,13 @@ public function read($address, $return_type = 'point', $bounds = FALSE, $return_
else {
$bounds_string = '';
}

$url = "http://maps.googleapis.com/maps/api/geocode/json";
$url .= '?address='. urlencode($address);
$url .= $bounds_string;
$url .= '&sensor=false';
$this->result = json_decode(@file_get_contents($url));

if ($this->result->status == 'OK') {
if ($return_multiple == FALSE) {
if ($return_type == 'point') {
Expand Down Expand Up @@ -93,12 +93,12 @@ public function write(Geometry $geometry, $return_type = 'string') {
$centroid = $geometry->getCentroid();
$lat = $centroid->getY();
$lon = $centroid->getX();

$url = "http://maps.googleapis.com/maps/api/geocode/json";
$url .= '?latlng='.$lat.','.$lon;
$url .= '&sensor=false';
$this->result = json_decode(@file_get_contents($url));

if ($this->result->status == 'OK') {
if ($return_type == 'string') {
return $this->result->results[0]->formatted_address;
Expand All @@ -107,13 +107,21 @@ public function write(Geometry $geometry, $return_type = 'string') {
return $this->result->results[0]->address_components;
}
}
elseif ($this->result->status == 'ZERO_RESULTS') {
if ($return_type == 'string') {
return '';
}
if ($return_type == 'array') {
return $this->result->results;
}
}
else {
if ($this->result->status) throw new Exception('Error in Google Reverse Geocoder: '.$this->result->status);
else throw new Exception('Unknown error in Google Reverse Geocoder');
return FALSE;
}
}

private function getPoint($delta = 0) {
$lat = $this->result->results[$delta]->geometry->location->lat;
$lon = $this->result->results[$delta]->geometry->location->lng;
Expand Down Expand Up @@ -143,7 +151,7 @@ private function getTopRight($delta = 0) {
$lon = $this->result->results[$delta]->geometry->bounds->northeast->lng;
return new Point($lon, $lat);
}

private function getBottomLeft($delta = 0) {
$lat = $this->result->results[$delta]->geometry->bounds->southwest->lat;
$lon = $this->result->results[$delta]->geometry->bounds->southwest->lng;
Expand Down

0 comments on commit 9e9dd12

Please sign in to comment.