1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ptondereau\GoogleAddressConverter; |
4
|
|
|
|
5
|
|
|
use Ptondereau\GoogleAddressConverter\Builders\AddressQueryBuilder; |
6
|
|
|
use Ptondereau\GoogleAddressConverter\Builders\UrlBuilder; |
7
|
|
|
use Ptondereau\GoogleAddressConverter\Http\HttpClient; |
8
|
|
|
|
9
|
|
|
class GoogleMapsClient extends HttpClient |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @var string Google maps api endpoint. |
13
|
|
|
*/ |
14
|
|
|
protected $url = 'https://maps.googleapis.com/maps/api/geocode/json'; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @var string Your API KEY. |
18
|
|
|
*/ |
19
|
|
|
protected $apiKey; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* GoogleMapsClient constructor. |
23
|
|
|
* |
24
|
|
|
* @param string $apiKey |
25
|
|
|
* @param \Http\Client\HttpClient $httpClient |
26
|
|
|
* |
27
|
|
|
* @throws \InvalidArgumentException |
28
|
|
|
*/ |
29
|
12 |
|
public function __construct($apiKey, \Http\Client\HttpClient $httpClient = null) |
30
|
|
|
{ |
31
|
12 |
|
if (!$apiKey) { |
32
|
3 |
|
throw new \InvalidArgumentException('API Key is mandatory'); |
33
|
|
|
} |
34
|
|
|
|
35
|
9 |
|
$this->apiKey = $apiKey; |
36
|
9 |
|
parent::__construct($httpClient); |
37
|
9 |
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Get an array of longitude and latitude. |
41
|
|
|
* |
42
|
|
|
* @param Address $address |
43
|
|
|
* |
44
|
|
|
* @return array |
45
|
|
|
* @throws \InvalidArgumentException |
46
|
|
|
*/ |
47
|
6 |
|
public function getLatLong(Address $address) |
48
|
|
|
{ |
49
|
6 |
|
$url = UrlBuilder::createUrl($this->url, $this->apiKey, AddressQueryBuilder::createFromAddress($address)); |
50
|
|
|
|
51
|
6 |
|
$response = json_decode($this->get($url), true); |
52
|
|
|
|
53
|
|
|
if ( |
54
|
6 |
|
!isset($response['results'][0]['geometry']['location']['lat']) |
55
|
5 |
|
&& !isset($response['results'][0]['geometry']['location']['lng']) |
56
|
4 |
|
) { |
57
|
3 |
|
throw new \InvalidArgumentException('Address parameters are wrong!'); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
return [ |
61
|
3 |
|
'lat' => $response['results'][0]['geometry']['location']['lat'], |
62
|
3 |
|
'lng' => $response['results'][0]['geometry']['location']['lng'], |
63
|
2 |
|
]; |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|