Skip to content

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 3 commits into from
Sep 29, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ providing a powerful abstraction layer for geocoding manipulations.
- [GeoIP2](#geoip2)
- [GoogleMaps](#googlemaps)
- [GoogleMapsBusiness](#googlemapsbusiness)
- [Mapzen](#mapzen)
- [MaxMindBinary](#maxmindbinary)
- [Nominatim](#nominatim)
- [TomTom](#tomtom)
Expand Down Expand Up @@ -239,7 +240,8 @@ Chain | `chain` | | | | | meta provider which iterates over a list of providers
[Geonames](http://www.geonames.org/commercial-webservices.html) | `geonames` | yes |no | worldwide | yes | requires registration, no free tier
[Google Maps](https://developers.google.com/maps/documentation/geocoding/) | `google_maps` | yes | supported | worldwide | yes | requires API key. Limit 2500 requests per day
[Google Maps for Business](https://developers.google.com/maps/documentation/business/) | `google_maps_business` | yes | supported | worldwide | yes | requires API key. Limit 100,000 requests per day
[MapQuest](http://developer.mapquest.com/web/products/dev-services/geocoding-ws) | `map_quest` | yes | no | worldwide | yes | both open and [commercial service](http://platform.mapquest.com/geocoding/) require API key
[MapQuest](http://developer.mapquest.com/web/products/dev-services/geocoding-ws) | `map_quest` | yes | no | worldwide | yes | both open and [commercial service](http://platform.mapquest.com/geocoding/) requires API key
[Mapzen](https://mapzen.com/documentation/search/) | `mapzen` | yes | supported | worldwide | yes | requires API key; limited to 6 request/sec, 30,000 request/day
[Nominatim](http://wiki.openstreetmap.org/wiki/Nominatim) | `nominatim` | yes | supported | worldwide | yes | requires a domain name (e.g. local installation)
[OpenCage](http://geocoder.opencagedata.com/) | `opencage` | yes | supported | worldwide | yes | requires API key. 2500 requests/day free
[OpenStreetMap](http://wiki.openstreetmap.org/wiki/Nominatim) | `openstreetmap` | yes | no | worldwide | yes | heavy users (>1q/s) get banned
Expand Down Expand Up @@ -296,6 +298,10 @@ $geocoder = new \Geocoder\Provider\GoogleMaps(
A valid `Client ID` is required. The private key is optional. This provider also
supports SSL, and extends the `GoogleMaps` provider.

##### Mapzen

A valid `API key` is required. This provider also supports SSL.

##### MaxMindBinary

This provider requires a data file, and the
Expand Down Expand Up @@ -524,7 +530,7 @@ Version `3.x` is the current major stable version of Geocoder.
Cookbook
--------

We have a small cookbook where you can find examples on common use cases:
We have a small cookbook where you can find examples on common use cases:

* [Caching responses](/docs/cookbook/cache.md)
* [Configuring the HTTP client](/docs/cookbook/http-client.md)
Expand Down
1 change: 1 addition & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
<!-- <server name="TOMTOM_MAP_KEY" value="YOUR_MAP_KEY" /> -->
<!-- <server name="GOOGLE_GEOCODING_KEY" value="YOUR_GEOCODING_KEY" /> -->
<!-- <server name="OPENCAGE_API_KEY" value="YOUR_GEOCODING_KEY" /> -->
<!-- <server name="MAPZEN_API_KEY" value="YOUR_MAPZEN_API_KEY" /> -->

</php>
<testsuites>
Expand Down
223 changes: 223 additions & 0 deletions src/Geocoder/Provider/Mapzen.php
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
Copy link
Contributor

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.

Copy link
Member Author

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?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

definitely yes!

Copy link
Member Author

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?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am +1

Copy link
Contributor

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.

{
/**
* @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;
}
}
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]}";
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]}";
Loading