Skip to content

Instantly share code, notes, and snippets.

@misaon
Created May 25, 2017 11:13
Show Gist options
  • Save misaon/4c1239f3ea77e421a36b0299115f9ddd to your computer and use it in GitHub Desktop.
Save misaon/4c1239f3ea77e421a36b0299115f9ddd to your computer and use it in GitHub Desktop.
Convert address to coordinates
<?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