Created
May 25, 2017 11:13
-
-
Save misaon/4c1239f3ea77e421a36b0299115f9ddd to your computer and use it in GitHub Desktop.
Convert address to coordinates
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 | |
namespace Sheansro\Models; | |
/** | |
* Class AddressToCoordinates | |
* @package Sheansro\Models | |
* @author Ondřej Misák <email@ondrejmisak.cz> | |
*/ | |
class AddressToCoordinates | |
{ | |
const GOOGLE_MAP_API_URL = 'https://maps.google.com/maps/api/geocode/json?sensor=false&address='; | |
/** | |
* @param $address | |
* | |
* @return null|array | |
*/ | |
public static function convert($address) | |
{ | |
/** | |
* Replace all the white space with "+" sign to match with google search pattern | |
*/ | |
$modifiedAddress = str_replace(' ', '+', $address); | |
/** | |
* Get response from API | |
*/ | |
$response = file_get_contents(self::GOOGLE_MAP_API_URL . $modifiedAddress); | |
/** | |
* Convert JSON response to array | |
*/ | |
$jsonResponse = json_decode($response, true); | |
if (!$jsonResponse || $jsonResponse['status'] !== 'OK') { | |
return null; | |
} | |
return [ | |
'lat' => (float)$jsonResponse['results'][0]['geometry']['location']['lat'], | |
'lng' => (float)$jsonResponse['results'][0]['geometry']['location']['lng'], | |
]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment