-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMapQuest.php
430 lines (348 loc) · 13 KB
/
MapQuest.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
<?php
declare(strict_types=1);
/*
* This file is part of the Geocoder package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
namespace Geocoder\Provider\MapQuest;
use Geocoder\Collection;
use Geocoder\Exception\InvalidArgument;
use Geocoder\Exception\InvalidCredentials;
use Geocoder\Exception\InvalidServerResponse;
use Geocoder\Exception\QuotaExceeded;
use Geocoder\Exception\UnsupportedOperation;
use Geocoder\Http\Provider\AbstractHttpProvider;
use Geocoder\Location;
use Geocoder\Model\Address;
use Geocoder\Model\AddressCollection;
use Geocoder\Model\AdminLevel;
use Geocoder\Model\Bounds;
use Geocoder\Model\Country;
use Geocoder\Provider\Provider;
use Geocoder\Query\GeocodeQuery;
use Geocoder\Query\ReverseQuery;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\ResponseInterface;
/**
* @author William Durand <[email protected]>
*/
final class MapQuest extends AbstractHttpProvider implements Provider
{
public const DATA_KEY_ADDRESS = 'address';
public const KEY_API_KEY = 'key';
public const KEY_LOCATION = 'location';
public const KEY_OUT_FORMAT = 'outFormat';
public const KEY_MAX_RESULTS = 'maxResults';
public const KEY_THUMB_MAPS = 'thumbMaps';
public const KEY_INTL_MODE = 'intlMode';
public const KEY_BOUNDING_BOX = 'boundingBox';
public const KEY_LAT = 'lat';
public const KEY_LNG = 'lng';
public const MODE_5BOX = '5BOX';
public const OPEN_BASE_URL = 'https://open.mapquestapi.com/geocoding/v1/';
public const LICENSED_BASE_URL = 'https://www.mapquestapi.com/geocoding/v1/';
public const GEOCODE_ENDPOINT = 'address';
public const DEFAULT_GEOCODE_PARAMS = [
self::KEY_LOCATION => '',
self::KEY_OUT_FORMAT => 'json',
self::KEY_API_KEY => '',
];
public const DEFAULT_GEOCODE_OPTIONS = [
self::KEY_MAX_RESULTS => 3,
self::KEY_THUMB_MAPS => false,
];
public const REVERSE_ENDPOINT = 'reverse';
public const ADMIN_LEVEL_STATE = 1;
public const ADMIN_LEVEL_COUNTY = 2;
/**
* MapQuest offers two geocoding endpoints one commercial (true) and one open (false)
* More information: http://developer.mapquest.com/web/tools/getting-started/platform/licensed-vs-open.
*
* @var bool
*/
private $licensed;
/**
* @var bool
*/
private $useRoadPosition;
/**
* @var string
*/
private $apiKey;
/**
* @param ClientInterface $client an HTTP adapter
* @param string $apiKey an API key
* @param bool $licensed true to use MapQuest's licensed endpoints, default is false to use the open endpoints (optional)
* @param bool $useRoadPosition true to use nearest point on a road for the entrance, false to use map display position
*/
public function __construct(ClientInterface $client, string $apiKey, bool $licensed = false, bool $useRoadPosition = false)
{
if (empty($apiKey)) {
throw new InvalidCredentials('No API key provided.');
}
$this->apiKey = $apiKey;
$this->licensed = $licensed;
$this->useRoadPosition = $useRoadPosition;
parent::__construct($client);
}
public function geocodeQuery(GeocodeQuery $query): Collection
{
$params = static::DEFAULT_GEOCODE_PARAMS;
$params[static::KEY_API_KEY] = $this->apiKey;
$options = static::DEFAULT_GEOCODE_OPTIONS;
$options[static::KEY_MAX_RESULTS] = $query->getLimit();
$useGetQuery = true;
$address = $this->extractAddressFromQuery($query);
if ($address instanceof Location) {
$params[static::KEY_LOCATION] = $this->mapAddressToArray($address);
$options[static::KEY_INTL_MODE] = static::MODE_5BOX;
$useGetQuery = false;
} else {
$addressAsText = $query->getText();
if (!$addressAsText) {
throw new InvalidArgument('Cannot geocode empty address');
}
// This API doesn't handle IPs
if (filter_var($addressAsText, FILTER_VALIDATE_IP)) {
throw new UnsupportedOperation('The MapQuest provider does not support IP addresses, only street addresses.');
}
$params[static::KEY_LOCATION] = $addressAsText;
}
$bounds = $query->getBounds();
if ($bounds instanceof Bounds) {
$options[static::KEY_BOUNDING_BOX] = $this->mapBoundsToArray($bounds);
$useGetQuery = false;
}
if ($useGetQuery) {
$params = $this->addOptionsForGetQuery($params, $options);
return $this->executeGetQuery(static::GEOCODE_ENDPOINT, $params);
} else {
$params = $this->addOptionsForPostQuery($params, $options);
return $this->executePostQuery(static::GEOCODE_ENDPOINT, $params);
}
}
public function reverseQuery(ReverseQuery $query): Collection
{
$coordinates = $query->getCoordinates();
$longitude = $coordinates->getLongitude();
$latitude = $coordinates->getLatitude();
$params = [
static::KEY_API_KEY => $this->apiKey,
static::KEY_LAT => $latitude,
static::KEY_LNG => $longitude,
];
return $this->executeGetQuery(static::REVERSE_ENDPOINT, $params);
}
public function getName(): string
{
return 'map_quest';
}
private function extractAddressFromQuery(GeocodeQuery $query): mixed
{
return $query->getData(static::DATA_KEY_ADDRESS);
}
private function getUrl(string $endpoint): string
{
if ($this->licensed) {
$baseUrl = static::LICENSED_BASE_URL;
} else {
$baseUrl = static::OPEN_BASE_URL;
}
return $baseUrl.$endpoint;
}
/**
* @param array<string, mixed> $params
*/
private function addGetQuery(string $url, array $params): string
{
return $url.'?'.http_build_query($params, '', '&', PHP_QUERY_RFC3986);
}
/**
* @param array<string, mixed> $params
* @param array<string, mixed> $options
*
* @return array<string, mixed>
*/
private function addOptionsForGetQuery(array $params, array $options): array
{
foreach ($options as $key => $value) {
if (false === $value) {
$value = 'false';
} elseif (true === $value) {
$value = 'true';
}
$params[$key] = $value;
}
return $params;
}
/**
* @param array<string, mixed> $params
* @param array<string, mixed> $options
*
* @return array<string, mixed>
*/
private function addOptionsForPostQuery(array $params, array $options): array
{
$params['options'] = $options;
return $params;
}
/**
* @param array<string, mixed> $params
*/
private function executePostQuery(string $endpoint, array $params): AddressCollection
{
$url = $this->getUrl($endpoint);
$appKey = $params[static::KEY_API_KEY];
unset($params[static::KEY_API_KEY]);
$url .= '?key='.$appKey;
$requestBody = json_encode($params);
$request = $this->createRequest('POST', $url, [], $requestBody);
$response = $this->getHttpClient()->sendRequest($request);
$content = $this->parseHttpResponse($response, $url);
return $this->parseResponseContent($content);
}
/**
* @param array<string, mixed> $params
*/
private function executeGetQuery(string $endpoint, array $params): AddressCollection
{
$baseUrl = $this->getUrl($endpoint);
$url = $this->addGetQuery($baseUrl, $params);
$content = $this->getUrlContents($url);
return $this->parseResponseContent($content);
}
private function parseResponseContent(string $content): AddressCollection
{
$json = json_decode($content, true);
if (!isset($json['results']) || empty($json['results'])) {
return new AddressCollection([]);
}
$locations = $json['results'][0]['locations'];
if (empty($locations)) {
return new AddressCollection([]);
}
$results = [];
foreach ($locations as $location) {
if ($location['street'] || $location['postalCode'] || $location['adminArea5'] || $location['adminArea4'] || $location['adminArea3']) {
$admins = [];
$state = $location['adminArea3'];
if ($state) {
$code = null;
if (2 == strlen($state)) {
$code = $state;
}
$admins[] = [
'name' => $state,
'code' => $code,
'level' => static::ADMIN_LEVEL_STATE,
];
}
if ($location['adminArea4']) {
$admins[] = ['name' => $location['adminArea4'], 'level' => static::ADMIN_LEVEL_COUNTY];
}
$position = $location['latLng'];
if (!$this->useRoadPosition) {
if ($location['displayLatLng']) {
$position = $location['displayLatLng'];
}
}
$results[] = Address::createFromArray([
'providedBy' => $this->getName(),
'latitude' => $position['lat'],
'longitude' => $position['lng'],
'streetName' => $location['street'] ?: null,
'locality' => $location['adminArea5'] ?: null,
'subLocality' => $location['adminArea6'] ?: null,
'postalCode' => $location['postalCode'] ?: null,
'adminLevels' => $admins,
'country' => $location['adminArea1'] ?: null,
'countryCode' => $location['adminArea1'] ?: null,
]);
}
}
return new AddressCollection($results);
}
/**
* @return array<string, mixed>
*/
private function mapAddressToArray(Location $address): array
{
$location = [];
$streetParts = [
trim($address->getStreetNumber() ?: ''),
trim($address->getStreetName() ?: ''),
];
$street = implode(' ', array_filter($streetParts));
if ($street) {
$location['street'] = $street;
}
if ($address->getSubLocality()) {
$location['adminArea6'] = $address->getSubLocality();
$location['adminArea6Type'] = 'Neighborhood';
}
if ($address->getLocality()) {
$location['adminArea5'] = $address->getLocality();
$location['adminArea5Type'] = 'City';
}
/** @var AdminLevel $adminLevel */
foreach ($address->getAdminLevels() as $adminLevel) {
switch ($adminLevel->getLevel()) {
case static::ADMIN_LEVEL_STATE:
$state = $adminLevel->getCode();
if (!$state) {
$state = $adminLevel->getName();
}
$location['adminArea3'] = $state;
$location['adminArea3Type'] = 'State';
break;
case static::ADMIN_LEVEL_COUNTY:
$county = $adminLevel->getName();
$location['adminArea4'] = $county;
$location['adminArea4Type'] = 'County';
}
}
$country = $address->getCountry();
if ($country instanceof Country) {
$code = $country->getCode();
if (!$code) {
$code = $country->getName();
}
$location['adminArea1'] = $code;
$location['adminArea1Type'] = 'Country';
}
$postalCode = $address->getPostalCode();
if ($postalCode) {
$location['postalCode'] = $address->getPostalCode();
}
return $location;
}
/**
* @return array<string, array<string,float>>
*/
private function mapBoundsToArray(Bounds $bounds): array
{
return [
'ul' => [static::KEY_LAT => $bounds->getNorth(), static::KEY_LNG => $bounds->getWest()],
'lr' => [static::KEY_LAT => $bounds->getSouth(), static::KEY_LNG => $bounds->getEast()],
];
}
protected function parseHttpResponse(ResponseInterface $response, string $url): string
{
$statusCode = $response->getStatusCode();
if (401 === $statusCode || 403 === $statusCode) {
throw new InvalidCredentials();
} elseif (429 === $statusCode) {
throw new QuotaExceeded();
} elseif ($statusCode >= 300) {
throw InvalidServerResponse::create($url, $statusCode);
}
$body = (string) $response->getBody();
if (empty($body)) {
throw InvalidServerResponse::emptyResponse($url);
}
return $body;
}
}