Skip to content

Instantly share code, notes, and snippets.

@ZhandosKz
Last active December 24, 2015 04:39
Show Gist options
  • Save ZhandosKz/6745376 to your computer and use it in GitHub Desktop.
Save ZhandosKz/6745376 to your computer and use it in GitHub Desktop.
google maps v3 geocoder
<?php
class Geocoder
{
public static $url = 'http://maps.googleapis.com/maps/api/geocode/json';
public function performRequest($search)
{
$url = sprintf("%s?address=%s&sensor=false", self::$url, urlencode($search));
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
public function getCity(stdClass $response) {
if (!isset($response->status) || !isset($response->results) || $response->status !== 'OK') {
return false;
}
$result = current($response->results);
foreach ($result->address_components as $address) {
if (in_array('administrative_area_level_2', $address->types)) {
return $address->long_name;
}
}
return false;
}
public function getCoords(stdClass $response) {
if (!isset($response->status) || !isset($response->results) || $response->status !== 'OK') {
return false;
}
return array(
'lat' => $response->geometry->location->lat,
'lng' => $response->geometry->location->lng
);
}
}
$geo = new Geocoder();
$json = $geo->performRequest('7800 Titus Boulevard, Fort Carson, CO, 80913, United States');
$city = $geo->getCity(json_decode($json));
$coords = $geo->getCity(json_decode($json));
var_dump($city);
var_dump($coords);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment