Last active
December 24, 2015 04:39
-
-
Save ZhandosKz/6745376 to your computer and use it in GitHub Desktop.
google maps v3 geocoder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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