Giter VIP home page Giter VIP logo

geocoder's Introduction

Geocoder

Build Status Total Downloads Latest Stable Version

Geocoder is a PHP library which helps you build geo-aware applications by providing a powerful abstraction layer for geocoding manipulations.

Providers

Providers perform the geocoding black magic for you (talking to the APIs, fetching results, dealing with errors, etc.) an are highly configurable.

Address-based Providers

Provider Name Reverse? SSL? Coverage Terms
ArcGIS Online arcgis_online yes supported worldwide requires API key. 1250 requests free
Bing Maps bing_maps yes no worldwide requires API key. Limit 10,000 requests per month
Chain chain meta provider which iterates over a list of providers
Geonames geonames yes no worldwide requires registration, no free tier
Google Maps google_maps yes supported worldwide requires API key. Limit 2500 requests per day
Google Maps for Business google_maps_business yes supported worldwide requires API key. Limit 100,000 requests per day
MapQuest map_quest yes no worldwide both open and commercial service require API key
Nominatim nominatim yes supported worldwide requires a domain name (e.g. local installation)
OpenCage opencage yes supported worldwide requires API key. 2500 requests/day free
OpenStreetMap openstreetmap yes no worldwide heavy users (>1q/s) get banned
TomTom tomtom yes required worldwide requires API key. First 2500 requests or 30 days free
Yandex yandex yes no worldwide

IP-based Providers

Provider Name IPv4? IPv6? Terms Notes
FreeGeoIp free_geo_ip yes yes
GeoIPs geo_ips yes no requires API key
GeoIP2 (Maxmind) maxmind_geoip2 yes yes
GeoPlugin geo_plugin yes  yes
HostIp host_ip yes no
IpInfoDB ip_info_db yes no requires API key. city precision
Geoip geoip wrapper around the PHP extension which must be installed
MaxMind web service maxmind yes yes requires Omni API key City/ISP/Org and Omni services, IPv6 on country level
MaxMind Binary file maxmind_binary yes yes needs locally installed database files

Important: the Geocoder Extra library contains even more official providers!

HTTP Adapters

In order to talk to geocoding APIs, you need HTTP adapters. While it was part of the library in Geocoder 1.x and 2.x, Geocoder 3.x and upper now relies on the PSR-7 Standard which defines how HTTP message should be implemented. Choose any library that follows this PSR and implement the specified interfaces to use with Geocoder.

As making choices is rather hard, Geocoder ships with the egeloen/http-adapter library by default, but it is up to you to choose a different implementation.

Note: not all providers are HTTP-based.

Installation

The recommended way to install Geocoder is through Composer:

$ composer require willdurand/geocoder

Usage

Geocoder and its companion Geocoder Extra provides a lot of providers.

Choose the one that fits your need first. Let's say the GoogleMaps one is what you were looking for, so let's see how to use it. In the code snippet below, curl has been choosen as HTTP layer but it is up to you since each HTTP-based provider implements PSR-7.

$curl     = new \Ivory\HttpAdapter\CurlHttpAdapter();
$geocoder = new \Geocoder\Provider\GoogleMaps($curl);

$geocoder->geocode(...);
$geocoder->reverse(...);

The Geocoder interface, which all providers implement, exposes two main methods:

  • geocode($streetOrIpAddress)
  • reverse($latitude, $longitude)

It also contains methods to control the number of results:

  • limit($limit)
  • getLimit()

Both geocode() and reverse() methods return an array of Address objects, each providing the following API:

  • getCoordinates() will return a Coordinates object (with latitude and longitude properties);
  • getLatitude() will return the latitude value;
  • getLongitude() will return the longitude value;
  • getBounds() will return an Bounds object (with south, west, north and east properties);
  • getStreetNumber() will return the street number/house number value;
  • getStreetName() will return the street name value;
  • getLocality() will return the locality or city;
  • getPostalCode() will return the postalCode or zipcode;
  • getSubLocality() will return the city district, or sublocality;
  • getCounty() will return a County object (with name and code properties);
  • getCountyCode() will return the county code (county short name);
  • getRegion() will return a Region object (with name and code properties);
  • getRegionCode() will return the region code (region short name);
  • getCountry() will return a Country object (with name and code properties);
  • getCountryCode() will return the ISO country code;
  • getTimezone() will return the timezone.

Locale Aware Providers

Providers that are locale aware expose the following methods:

$geocoder->setLocale('xyz');

$locale = $geocoder->getLocale();

GoogleMaps

Locale and/or region can be specified:

$geocoder = new \Geocoder\Provider\GoogleMaps(
    $httpAdapter,
    $locale,
    $region,
    $useSsl // true|false
);

GoogleMapsBusiness

A valid Client ID is required. The private key is optional. This provider also supports SSL, and extends the GoogleMaps provider.

Nominatim

Access to a Nominatim server is required. See the Nominatim Wiki Page for more information.

Yandex

The default language-locale is ru-RU, you can choose between uk-UA, be-BY, en-US, en-BR and tr-TR. This provider can also reverse information based on coordinates (latitude, longitude). It's possible to precise the toponym to get more accurate result for reverse geocoding: house, street, metro, district and locality.

MaxMindBinary

This provider requires a data file, and the geoip/geoip package must be installed.

It is worth mentioning that this provider has serious performance issues, and should not be used in production. For more information, please read issue #301.

GeoIP2

It requires either the database file, or the webservice - represented by the GeoIP2 , which is injected to the GeoIP2Adapter. The geoip2/geoip2 package must be installed.

This provider will only work with the corresponding GeoIP2Adapter:

<?php

// Maxmind GeoIP2 Provider: e.g. the database reader
$reader   = new \GeoIp2\Database\Reader('/path/to/database');

$adapter  = new \Geocoder\Adapter\GeoIP2Adapter($reader);
$geocoder = new \Geocoder\Provider\GeoIP2($adapter);

$address   = $geocoder->geocode('74.200.247.59');

TomTom

The default langage-locale is en, you can choose between de, es, fr, it, nl, pl, pt and sv.

ArcGISOnline

It is possible to specify a sourceCountry to restrict result to this specific country thus reducing request time (note that this doesn't work on reverse geocoding).

The ProviderAggregator

The ProviderAggregator is used to register several providers so that you can decide which provider to use later on.

<?php

$geocoder = new \Geocoder\ProviderAggregator();

$geocoder->registerProviders([
    new \Geocoder\Provider\GoogleMaps(
        $adapter, $locale, $region, $useSsl
    ),
    new \Geocoder\Provider\GoogleMapsBusiness(
        $adapter, '<CLIENT_ID>', '<PRIVATE_KEY>', $locale, $region, $useSsl
    ),
    new \Geocoder\Provider\Yandex(
        $adapter, $locale, $toponym
    ),
    new \Geocoder\Provider\MaxMind(
        $adapter, '<MAXMIND_API_KEY>', $service, $useSsl
    ),
    new \Geocoder\Provider\ArcGISOnline(
        $adapter, $sourceCountry, $useSsl
    ),
]);

$geocoder->registerProvider(
    new \Geocoder\Provider\Nominatim(
        $adapter, 'http://your.nominatim.server', $locale
    )
);

$geocoder
    ->using('google_maps')
    ->geocode('...');

$geocoder
    ->limit(10)
    ->reverse($lat, $lng);

The ProviderAggregator's API is fluent, meaning you can write:

<?php

$addresses = $geocoder
    ->registerProvider(new \My\Provider\Custom($adapter))
    ->using('custom')
    ->limit(10)
    ->geocode('68.145.37.34')
    ;

The using() method allows you to choose the provider to use by its name. When you deal with multiple providers, you may want to choose one of them. The default behavior is to use the first one but it can be annoying.

The limit() method allows you to configure the maximum number of results being returned. Depending on the provider you may not get as many results as expected, it is a maximum limit, not the expected number of results.

The Chain Provider

The Chain provider is a special provider that takes a list of providers and iterates over this list to get information. Note that it stops its iteration when a provider returns a result. The result is returned by GoogleMaps because FreeGeoIp and HostIp cannot geocode street addresses. BingMaps is ignored.

$geocoder = new \Geocoder\ProviderAggregator();
$adapter  = new \Ivory\HttpAdapter\CurlHttpAdapter();

$chain = new \Geocoder\Provider\Chain([
    new \Geocoder\Provider\FreeGeoIp($adapter),
    new \Geocoder\Provider\HostIp($adapter),
    new \Geocoder\Provider\GoogleMaps($adapter, 'fr_FR', 'France', true),
    new \Geocoder\Provider\BingMaps($adapter, '<API_KEY>'),
    // ...
]);

$geocoder->registerProvider($chain);

try {
    $geocode = $geocoder->geocode('10 rue Gambetta, Paris, France');
    var_export($geocode);
} catch (Exception $e) {
    echo $e->getMessage();
}

Everything is ok, enjoy!

Dumpers

Geocoder provides dumpers that aim to transform an Address object in standard formats.

GPS eXchange Format (GPX)

The GPS eXchange format is designed to share geolocated data like point of interests, tracks, ways, but also coordinates. Geocoder provides a dumper to convert an Address object in an GPX compliant format.

Assuming we got a $address object as seen previously:

<?php

$dumper = new \Geocoder\Dumper\Gpx();
$strGpx = $dumper->dump($address);

echo $strGpx;

It will display:

<gpx
    version="1.0"
    creator="Geocoder" version="1.0.1-dev"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.topografix.com/GPX/1/0"
    xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd">
    <bounds minlat="2.388911" minlon="48.863151" maxlat="2.388911" maxlon="48.863151"/>
    <wpt lat="48.8631507" lon="2.3889114">
        <name><![CDATA[Paris]]></name>
        <type><![CDATA[Address]]></type>
    </wpt>
</gpx>

GeoJSON

GeoJSON is a format for encoding a variety of geographic data structures.

Keyhole Markup Language (KML)

Keyhole Markup Language is an XML notation for expressing geographic annotation and visualization within Internet-based, two-dimensional maps and three-dimensional Earth browsers.

Well-Known Binary (WKB)

The Well-Known Binary (WKB) representation for geometric values is defined by the OpenGIS specification.

Well-Known Text (WKT)

Well-known text (WKT) is a text markup language for representing vector geometry objects on a map, spatial reference systems of spatial objects and transformations between spatial reference systems.

Formatters

A common use case is to print geocoded data. Thanks to the StringFormatter class, it's simple to format an Address object as a string:

<?php

// $address is an instance of Address
$formatter = new \Geocoder\Formatter\StringFormatter();

$formatter->format($address, '%S %n, %z %L');
// 'Badenerstrasse 120, 8001 Zuerich'

$formatter->format($address, '<p>%S %n, %z %L</p>');
// '<p>Badenerstrasse 120, 8001 Zuerich</p>'

Here is the mapping:

  • Street Number: %n

  • Street Name: %S

  • City: %L

  • City District: %D

  • Zipcode: %z

  • County: %P

  • County Code: %p

  • Region: %R

  • Region Code: %r

  • Country: %C

  • Country Code: %c

  • Timezone: %T

Extending Things

You can write your own provider by implementing the Provider interface.

You can provide your own dumper by implementing the Dumper interface.

Contributing

See CONTRIBUTING file.

Unit Tests

In order to run the test suite, install the developement dependencies:

$ composer install --dev

Then, run the following command:

$ phpunit

You'll obtain some skipped unit tests due to the need of API keys.

Rename the phpunit.xml.dist file to phpunit.xml, then uncomment the following lines and add your own API keys:

<php>
    <!-- <server name="IPINFODB_API_KEY" value="YOUR_API_KEY" /> -->
    <!-- <server name="BINGMAPS_API_KEY" value="YOUR_API_KEY" /> -->
    <!-- <server name="GEOIPS_API_KEY" value="YOUR_API_KEY" /> -->
    <!-- <server name="MAXMIND_API_KEY" value="YOUR_API_KEY" /> -->
    <!-- <server name="GEONAMES_USERNAME" value="YOUR_USERNAME" /> -->
    <!-- <server name="TOMTOM_GEOCODING_KEY" value="YOUR_GEOCODING_KEY" /> -->
    <!-- <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_API_KEY" /> -->
</php>

You're done.

Credits

License

Geocoder is released under the MIT License. See the bundled LICENSE file for details.

geocoder's People

Contributors

andrea-cristaudo avatar baachi avatar baikunz avatar bschaeffer avatar clicktrend avatar gelolabs avatar gpirrotta avatar gromnan avatar gyndav avatar havvg avatar jsor avatar jszobody avatar kaiwa avatar kausheel avatar makasim avatar mattketmo avatar mtdowling avatar mtmail avatar nicolas-grekas avatar nnarhinen avatar ollietb avatar pyrech avatar ronanguilloux avatar staabm avatar themouette avatar toin0u avatar userabuser avatar vslinko avatar warmans avatar willdurand avatar

Stargazers

 avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.