Last active
March 31, 2019 03:53
-
-
Save jmillerdesign/1604737 to your computer and use it in GitHub Desktop.
Google Maps Geolocation
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 | |
/** | |
* GoogleGeo | |
* | |
* Google maps geolocation, to find coordinates of a location | |
* @author J. Miller | |
*/ | |
class GoogleGeo { | |
// GoogleMaps API Key | |
// http://www.google.com/apis/maps/signup.html | |
private $apiKey = GOOGLE_MAPS_API_KEY; | |
private $apiURL = 'http://maps.google.com/maps/geo?q={address}&key={key}'; | |
private $address = ''; | |
/** | |
* Constructor | |
* | |
* @param string $address (optional) Address to search for | |
* @return void | |
*/ | |
public function __construct($address = '') { | |
$this->address = $address; | |
} | |
/** | |
* Get details about a location | |
* | |
* @param string $address Location to search for. Enter as much information as possible. | |
* @return false|array Location found | |
* latitude | |
* longitude | |
* address | |
* state | |
* country | |
*/ | |
public function getLocationFromAddress($address = null) { | |
if (!$address) { | |
$address = $this->address; | |
if (!$address) { | |
throw new Exception('Missing address.'); | |
} | |
} | |
// Create API URL | |
$url = $this->apiURL; | |
$url = str_replace('{address}', urlencode($address), $url); | |
$url = str_replace('{key}', $this->apiKey, $url); | |
// Get response from API | |
$response = json_decode(file_get_contents($url)); | |
if ($response->Status->code == 200) { | |
// Received a location | |
$location = array( | |
'latitude' => $response->Placemark[0]->Point->coordinates[1], | |
'longitude' => $response->Placemark[0]->Point->coordinates[0], | |
'address' => $response->Placemark[0]->address, | |
'state' => $response->Placemark[0]->AddressDetails->Country->AdministrativeArea->AdministrativeAreaName, | |
'country' => $response->Placemark[0]->AddressDetails->Country->CountryNameCode | |
); | |
if (isset($response->Placemark[0]->AddressDetails->Country->AdministrativeArea->SubAdministrativeArea)) { | |
$location['city'] = $response->Placemark[0]->AddressDetails->Country->AdministrativeArea->SubAdministrativeArea->Locality->LocalityName; | |
$location['zip'] = $response->Placemark[0]->AddressDetails->Country->AdministrativeArea->SubAdministrativeArea->Locality->PostalCode->PostalCodeNumber; | |
} else { | |
$location['city'] = $response->Placemark[0]->AddressDetails->Country->AdministrativeArea->Locality->LocalityName; | |
$location['zip'] = $response->Placemark[0]->AddressDetails->Country->AdministrativeArea->Locality->PostalCode->PostalCodeNumber; | |
} | |
return $location; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment