-
Notifications
You must be signed in to change notification settings - Fork 522
Add support for Mapzen's Geocoder #531
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,223 @@ | ||
<?php | ||
|
||
/** | ||
* 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; | ||
|
||
use Geocoder\Exception\InvalidCredentials; | ||
use Geocoder\Exception\QuotaExceeded; | ||
use Geocoder\Exception\NoResult; | ||
use Geocoder\Exception\UnsupportedOperation; | ||
use Http\Client\HttpClient; | ||
|
||
/** | ||
* @author Gary Gale <[email protected]> | ||
*/ | ||
class Mapzen extends AbstractHttpProvider | ||
{ | ||
/** | ||
* @var string | ||
*/ | ||
const GEOCODE_ENDPOINT_URL = '%s://search.mapzen.com/v1/search?text=%s&key=%s&size=%d'; | ||
|
||
/** | ||
* @var string | ||
*/ | ||
const REVERSE_ENDPOINT_URL = '%s://search.mapzen.com/v1/reverse?point.lat=%f&point.lon=%f&key=%s&size=%d'; | ||
|
||
/** | ||
* @var string | ||
*/ | ||
private $scheme; | ||
|
||
/** | ||
* @var string | ||
*/ | ||
private $apiKey; | ||
|
||
/** | ||
* @param HttpClient $client An HTTP adapter. | ||
* @param string $apiKey An API key. | ||
* @param bool $useSsl Whether to use an SSL connection (optional). | ||
*/ | ||
public function __construct(HttpClient $client, $apiKey, $useSSL = true) | ||
{ | ||
parent::__construct($client); | ||
|
||
$this->apiKey = $apiKey; | ||
$this->scheme = $useSSL ? 'https' : 'http'; | ||
} | ||
|
||
/** | ||
* {@inheritdoc} | ||
*/ | ||
public function geocode($address) | ||
{ | ||
if (null === $this->apiKey) { | ||
throw new InvalidCredentials('No API Key provided.'); | ||
} | ||
|
||
// This API doesn't handle IPs | ||
if (filter_var($address, FILTER_VALIDATE_IP)) { | ||
throw new UnsupportedOperation('The Mapzen provider does not support IP addresses, only street addresses.'); | ||
} | ||
|
||
$query = sprintf(self::GEOCODE_ENDPOINT_URL, $this->scheme, urlencode($address), $this->apiKey, $this->getLimit()); | ||
|
||
return $this->executeQuery($query); | ||
} | ||
|
||
/** | ||
* {@inheritdoc} | ||
*/ | ||
public function reverse($latitude, $longitude) | ||
{ | ||
if (null === $this->apiKey) { | ||
throw new InvalidCredentials('No API Key provided.'); | ||
} | ||
|
||
$query = sprintf(self::REVERSE_ENDPOINT_URL, $this->scheme, $latitude, $longitude, $this->apiKey, $this->getLimit()); | ||
|
||
return $this->executeQuery($query); | ||
} | ||
|
||
/** | ||
* {@inheritdoc} | ||
*/ | ||
public function getName() | ||
{ | ||
return 'mapzen'; | ||
} | ||
|
||
/** | ||
* @param $query | ||
* @return \Geocoder\Model\AddressCollection | ||
*/ | ||
private function executeQuery($query) | ||
{ | ||
$request = $this->getMessageFactory()->createRequest('GET', $query); | ||
$content = (string) $this->getHttpClient()->sendRequest($request)->getBody(); | ||
|
||
if (empty($content)) { | ||
throw new NoResult(sprintf('Could not execute query "%s".', $query)); | ||
} | ||
|
||
$json = json_decode($content, true); | ||
|
||
// See https://mapzen.com/documentation/search/api-keys-rate-limits/ | ||
if (isset($json['meta'])) { | ||
switch ($json['meta']['status_code']) { | ||
case 403: | ||
throw new InvalidCredentials('Invalid or missing api key.'); | ||
case 429: | ||
throw new QuotaExceeded('Valid request but quota exceeded.'); | ||
} | ||
} | ||
|
||
if (!isset($json['type']) || $json['type'] !== 'FeatureCollection' || !isset($json['features']) || count($json['features']) === 0) { | ||
throw new NoResult(sprintf('Could not find results for query "%s".', $query)); | ||
} | ||
|
||
$locations = $json['features']; | ||
|
||
if (empty($locations)) { | ||
throw new NoResult(sprintf('Could not find results for query "%s".', $query)); | ||
} | ||
|
||
$results = []; | ||
foreach ($locations as $location) { | ||
$bounds = []; | ||
if (isset($location['bbox'])) { | ||
$bounds = [ | ||
'south' => $location['bbox'][3], | ||
'west' => $location['bbox'][2], | ||
'north' => $location['bbox'][1], | ||
'east' => $location['bbox'][0], | ||
]; | ||
} | ||
|
||
$props = $location['properties']; | ||
|
||
$adminLevels = []; | ||
foreach (['region', 'locality', 'macroregion', 'country'] as $i => $component) { | ||
if (isset($props[$component])) { | ||
$adminLevels[] = ['name' => $props[$component], 'level' => $i + 1]; | ||
} | ||
} | ||
|
||
$results[] = array_merge($this->getDefaults(), array( | ||
'latitude' => $location['geometry']['coordinates'][1], | ||
'longitude' => $location['geometry']['coordinates'][0], | ||
'bounds' => $bounds ?: [], | ||
'streetNumber' => isset($props['housenumber']) ? $props['housenumber'] : null, | ||
'streetName' => isset($props['street']) ? $props['street'] : null, | ||
'subLocality' => isset($props['neighbourhood']) ? $props['neighbourhood'] : null, | ||
'locality' => isset($props['locality']) ? $props['locality'] : null, | ||
'postalCode' => isset($props['postalcode']) ? $props['postalcode'] : null, | ||
'adminLevels' => $adminLevels, | ||
'country' => isset($props['country']) ? $props['country'] : null, | ||
'countryCode' => isset($props['country_a']) ? strtoupper($props['country_a']) : null | ||
)); | ||
} | ||
|
||
return $this->returnResults($results); | ||
} | ||
|
||
/** | ||
* @param array $components | ||
* | ||
* @return null|string | ||
*/ | ||
protected function guessLocality(array $components) | ||
{ | ||
$localityKeys = array('city', 'town' , 'village', 'hamlet'); | ||
|
||
return $this->guessBestComponent($components, $localityKeys); | ||
} | ||
|
||
/** | ||
* @param array $components | ||
* | ||
* @return null|string | ||
*/ | ||
protected function guessStreetName(array $components) | ||
{ | ||
$streetNameKeys = array('road', 'street', 'street_name', 'residential'); | ||
|
||
return $this->guessBestComponent($components, $streetNameKeys); | ||
} | ||
|
||
/** | ||
* @param array $components | ||
* | ||
* @return null|string | ||
*/ | ||
protected function guessSubLocality(array $components) | ||
{ | ||
$subLocalityKeys = array('neighbourhood', 'city_district'); | ||
|
||
return $this->guessBestComponent($components, $subLocalityKeys); | ||
} | ||
|
||
/** | ||
* @param array $components | ||
* @param array $keys | ||
* | ||
* @return null|string | ||
*/ | ||
protected function guessBestComponent(array $components, array $keys) | ||
{ | ||
foreach ($keys as $key) { | ||
if (isset($components[$key]) && !empty($components[$key])) { | ||
return $components[$key]; | ||
} | ||
} | ||
|
||
return null; | ||
} | ||
} |
1 change: 1 addition & 0 deletions
1
tests/.cached_responses/00a3bd9f9306c9ae3b8aa7aa0c85d71d6d5de8fa
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
s:3418:"{"geocoding":{"version":"0.1","attribution":"https://search.mapzen.com/v1/attribution","query":{"text":"Hanover","size":5,"private":false,"querySize":10},"engine":{"name":"Pelias","author":"Mapzen","version":"1.0"},"timestamp":1473682048001},"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[-88.204203,42.027323]},"properties":{"id":"404497623","gid":"whosonfirst:localadmin:404497623","layer":"localadmin","source":"whosonfirst","source_id":"404497623","name":"Hanover","confidence":0.951,"country":"United States","country_gid":"whosonfirst:country:85633793","country_a":"USA","region":"Illinois","region_gid":"whosonfirst:region:85688697","region_a":"IL","county":"Cook County","county_gid":"whosonfirst:county:102084317","localadmin":"Hanover","localadmin_gid":"whosonfirst:localadmin:404497623","label":"Hanover, IL, USA"},"bbox":[-88.263572,41.986227,-88.14458,42.067434]},{"type":"Feature","geometry":{"type":"Point","coordinates":[-78.122906,18.393428]},"properties":{"id":"85672563","gid":"whosonfirst:region:85672563","layer":"region","source":"whosonfirst","source_id":"85672563","name":"Hanover","confidence":0.944,"country":"Jamaica","country_gid":"whosonfirst:country:85632215","country_a":"JAM","region":"Hanover","region_gid":"whosonfirst:region:85672563","label":"Hanover, Jamaica"},"bbox":[-78.3460426069,18.2897883164,-77.9214139468,18.4554710959]},{"type":"Feature","geometry":{"type":"Point","coordinates":[-76.72414,39.19289]},"properties":{"id":"4357340","gid":"geonames:locality:4357340","layer":"locality","source":"geonames","source_id":"4357340","name":"Hanover","confidence":0.734,"country":"United States","country_gid":"whosonfirst:country:85633793","country_a":"USA","region":"Maryland","region_gid":"whosonfirst:region:85688501","region_a":"MD","county":"Howard County","county_gid":"whosonfirst:county:102084263","locality":"Hanover","locality_gid":"whosonfirst:locality:4357340","label":"Hanover, MD, USA"}},{"type":"Feature","geometry":{"type":"Point","coordinates":[-70.81199,42.11316]},"properties":{"id":"4938836","gid":"geonames:locality:4938836","layer":"locality","source":"geonames","source_id":"4938836","name":"Hanover","confidence":0.72,"country":"United States","country_gid":"whosonfirst:country:85633793","country_a":"USA","region":"Massachusetts","region_gid":"whosonfirst:region:85688645","region_a":"MA","county":"Plymouth County","county_gid":"whosonfirst:county:102084367","localadmin":"Hanover","localadmin_gid":"whosonfirst:localadmin:404476511","locality":"Hanover","locality_gid":"whosonfirst:locality:4938836","label":"Hanover, MA, USA"}},{"type":"Feature","geometry":{"type":"Point","coordinates":[-76.984032,39.81179]},"properties":{"id":"101717245","gid":"whosonfirst:locality:101717245","layer":"locality","source":"whosonfirst","source_id":"101717245","name":"Hanover","confidence":0.718,"country":"United States","country_gid":"whosonfirst:country:85633793","country_a":"USA","region":"Pennsylvania","region_gid":"whosonfirst:region:85688481","region_a":"PA","county":"York County","county_gid":"whosonfirst:county:102080953","localadmin":"Hanover","localadmin_gid":"whosonfirst:localadmin:404487771","locality":"Hanover","locality_gid":"whosonfirst:locality:101717245","label":"Hanover, PA, USA"},"bbox":[-76.999944,39.791156,-76.963061,39.831769]}],"bbox":[-88.263572,18.2897883164,-70.81199,42.11316]}"; |
1 change: 1 addition & 0 deletions
1
tests/.cached_responses/404ab562295927999aba94e1e615fca96186879e
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
s:4780:"{"geocoding":{"version":"0.1","attribution":"https://search.mapzen.com/v1/attribution","query":{"text":"242 Acklam Road, London, United Kingdom","parsed_text":{"name":"242 Acklam Road","number":"242","street":"Acklam Road","regions":["London","United Kingdom"],"admin_parts":"London, United Kingdom"},"size":5,"private":false,"querySize":10},"engine":{"name":"Pelias","author":"Mapzen","version":"1.0"},"timestamp":1473674363289},"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[-0.203602,51.521124]},"properties":{"id":"node:3711723386","gid":"openstreetmap:address:node:3711723386","layer":"address","source":"openstreetmap","source_id":"node:3711723386","name":"240 Acklam Road","housenumber":"240","street":"Acklam Road","postalcode":"W10 5QT","confidence":0.866,"country":"United Kingdom","country_gid":"whosonfirst:country:85633159","country_a":"GBR","macroregion":"England","macroregion_gid":"whosonfirst:macroregion:404227469","region":"Kensington and Chelsea","region_gid":"whosonfirst:region:85683667","locality":"London","locality_gid":"whosonfirst:locality:101750367","neighbourhood":"Westbourne Green","neighbourhood_gid":"whosonfirst:neighbourhood:85864267","label":"240 Acklam Road, London, England, United Kingdom"}},{"type":"Feature","geometry":{"type":"Point","coordinates":[-1.282082,54.552668]},"properties":{"id":"node:1485615866","gid":"openstreetmap:address:node:1485615866","layer":"address","source":"openstreetmap","source_id":"node:1485615866","name":"Teesdale Park Acklam Road","housenumber":"Teesdale Park","street":"Acklam Road","postalcode":"TS17 7JU","confidence":0.866,"country":"United Kingdom","country_gid":"whosonfirst:country:85633159","country_a":"GBR","macroregion":"England","macroregion_gid":"whosonfirst:macroregion:404227469","region":"Stockton-on-Tees","region_gid":"whosonfirst:region:85683777","localadmin":"Thornaby","localadmin_gid":"whosonfirst:localadmin:404452219","neighbourhood":"Acklam","neighbourhood_gid":"whosonfirst:neighbourhood:85785205","label":"Teesdale Park Acklam Road, Thornaby, England, United Kingdom"}},{"type":"Feature","geometry":{"type":"Point","coordinates":[-70.568928,41.565854]},"properties":{"id":"us/ma/statewide:862559","gid":"openaddresses:address:us/ma/statewide:862559","layer":"address","source":"openaddresses","source_id":"us/ma/statewide:862559","name":"242 Acapesket Road","housenumber":"242","street":"Acapesket Road","postalcode":"02536","confidence":0.647,"country":"United States","country_gid":"whosonfirst:country:85633793","country_a":"USA","region":"Massachusetts","region_gid":"whosonfirst:region:85688645","region_a":"MA","county":"Barnstable County","county_gid":"whosonfirst:county:102084379","localadmin":"Falmouth","localadmin_gid":"whosonfirst:localadmin:404476181","locality":"East Falmouth","locality_gid":"whosonfirst:locality:85950545","neighbourhood":"Kingdom Hall","neighbourhood_gid":"whosonfirst:neighbourhood:85828363","label":"242 Acapesket Road, East Falmouth, MA, USA"}},{"type":"Feature","geometry":{"type":"Point","coordinates":[-72.492505,42.704231]},"properties":{"id":"us/ma/statewide:1436753","gid":"openaddresses:address:us/ma/statewide:1436753","layer":"address","source":"openaddresses","source_id":"us/ma/statewide:1436753","name":"242 Old Vernon Road","housenumber":"242","street":"Old Vernon Road","postalcode":"01360","confidence":0.647,"country":"United States","country_gid":"whosonfirst:country:85633793","country_a":"USA","region":"Massachusetts","region_gid":"whosonfirst:region:85688645","region_a":"MA","county":"Franklin County","county_gid":"whosonfirst:county:102084457","localadmin":"Northfield","localadmin_gid":"whosonfirst:localadmin:404475965","neighbourhood":"Satans Kingdom","neighbourhood_gid":"whosonfirst:neighbourhood:420523529","label":"242 Old Vernon Road, Northfield, MA, USA"}},{"type":"Feature","geometry":{"type":"Point","coordinates":[-70.528914,41.591705]},"properties":{"id":"us/ma/statewide:2148130","gid":"openaddresses:address:us/ma/statewide:2148130","layer":"address","source":"openaddresses","source_id":"us/ma/statewide:2148130","name":"242 Carriage Shop Road","housenumber":"242","street":"Carriage Shop Road","postalcode":"02536","confidence":0.647,"country":"United States","country_gid":"whosonfirst:country:85633793","country_a":"USA","region":"Massachusetts","region_gid":"whosonfirst:region:85688645","region_a":"MA","county":"Barnstable County","county_gid":"whosonfirst:county:102084379","localadmin":"Falmouth","localadmin_gid":"whosonfirst:localadmin:404476181","neighbourhood":"Kingdom Hall","neighbourhood_gid":"whosonfirst:neighbourhood:85828363","label":"242 Carriage Shop Road, Falmouth, MA, USA"}}],"bbox":[-72.492505,41.565854,-0.203602,54.552668]}"; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It makes sense to finalize this class.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That's true; it probably does. However when I wrote this I used the existing provider implementations as examples of best practice and as far as I can see, none of these finalise their classes. Not that's not a good reason not to do this, but I would have thought it would make more sense to apply finalisation across the board, rather than have a single provider finalise and none of the others doing so.
Thoughts?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
definitely yes!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I've just opened a new issue (#537) so we track adding finalisation to all providers. But I'm also assuming that based on @willdurand's comment above, there's nothing stopping this PR from being merged now?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I am +1
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
So far this is the only provider without
final
keyword.