|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace KamranAhmed\Geocode; |
|
4
|
|
|
|
|
5
|
|
|
/** |
|
6
|
|
|
* A wrapper around Google's Geocode API that parses the address, |
|
7
|
|
|
* to get different details regarding the address |
|
8
|
|
|
* |
|
9
|
|
|
* @author Kamran Ahmed <[email protected]> |
|
10
|
|
|
* @license http://www.opensource.org/licenses/MIT |
|
11
|
|
|
* @version v2.0 |
|
12
|
|
|
*/ |
|
13
|
|
|
class Geocode |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* API URL through which the address will be obtained. |
|
17
|
|
|
*/ |
|
18
|
|
|
private $serviceUrl = "://maps.googleapis.com/maps/api/geocode/json?"; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* Array containing the query results |
|
22
|
|
|
*/ |
|
23
|
|
|
private $serviceResults; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* Constructor |
|
27
|
|
|
* |
|
28
|
|
|
* @param string $key Google Maps Geocoding API key |
|
29
|
|
|
*/ |
|
30
|
6 |
|
public function __construct($key = '') |
|
31
|
|
|
{ |
|
32
|
6 |
|
$this->serviceUrl = (!empty($key)) |
|
33
|
6 |
|
? 'https' . $this->serviceUrl . "key={$key}" |
|
34
|
6 |
|
: 'http' . $this->serviceUrl; |
|
35
|
6 |
|
} |
|
36
|
|
|
|
|
37
|
|
|
/** |
|
38
|
|
|
* Returns the private $serviceUrl |
|
39
|
|
|
* |
|
40
|
|
|
* @return string The service URL |
|
41
|
|
|
*/ |
|
42
|
5 |
|
public function getServiceUrl() |
|
43
|
|
|
{ |
|
44
|
5 |
|
return $this->serviceUrl; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* Sends request to the passed Google Geocode API URL and fetches the address details and returns them |
|
49
|
|
|
* |
|
50
|
|
|
* @param $address |
|
51
|
|
|
* |
|
52
|
|
|
* @return bool|object false if no data is returned by URL and the detail otherwise |
|
53
|
|
|
* @throws \Exception |
|
54
|
|
|
* @internal param string $url Google geocode API URL containing the address or latitude/longitude |
|
55
|
|
|
*/ |
|
56
|
4 |
|
public function get($address) |
|
57
|
|
|
{ |
|
58
|
4 |
|
if (empty($address)) { |
|
59
|
1 |
|
throw new \Exception("Address is required in order to process"); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
3 |
|
$url = $this->getServiceUrl() . "&address=" . urlencode($address); |
|
63
|
3 |
|
$ch = curl_init(); |
|
64
|
|
|
|
|
65
|
3 |
|
curl_setopt($ch, CURLOPT_URL, $url); |
|
66
|
3 |
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); |
|
67
|
|
|
|
|
68
|
3 |
|
$serviceResults = json_decode(curl_exec($ch)); |
|
69
|
3 |
|
if ($serviceResults && $serviceResults->status === 'OK') { |
|
70
|
1 |
|
$this->serviceResults = $serviceResults; |
|
71
|
|
|
|
|
72
|
1 |
|
return new Location($address, $this->serviceResults); |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
2 |
|
return new Location($address, new \stdClass); |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|