Skip to content

Instantly share code, notes, and snippets.

@maesa
Created May 4, 2014 11:44
Show Gist options
  • Select an option

  • Save maesa/ec36275540d86bf85a0a to your computer and use it in GitHub Desktop.

Select an option

Save maesa/ec36275540d86bf85a0a to your computer and use it in GitHub Desktop.
Simple geocoding CodeIgniter library using Google Maps API v3
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class GoogleGeocoder
{
public function __construct()
{
$this->baseURL = "https://maps.google.com/maps/api/geocode/json?sensor=false";
}
public function geocode($address)
{
$url = $this->baseURL . "&address=" . urlencode($address);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec($ch);
curl_close($ch);
if ($contents) {
$resp = json_decode($contents);
if($resp->status = 'OK'){
return $resp->results[0]->geometry->location;
} else {
return FALSE;
}
} else {
return FALSE;
}
}
public function reverseGeocode($location)
{
$url = $this->baseURL . "&latlng=" . $location;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec($ch);
curl_close($ch);
if ($contents) {
$resp = json_decode($contents);
if($resp->status = 'OK'){
return $resp->results[0]->formatted_address;
} else {
return FALSE;
}
} else {
return FALSE;
}
}
}
?>
@JMichaelRoach
Copy link

Excellent! Much appreciated.

@plindsay
Copy link

Very handy (and short!) - many thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment