Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

The most featured Geocoder library written in PHP.

License

NotificationsYou must be signed in to change notification settings

SourceCode/Geocoder

 
 

Repository files navigation

Build StatusTotal DownloadsLatest Stable Version

Important: You are browsing the documentation of Geocoder3.x.Documentation for version2.x is available here:Geocoder 2.xdocumentation.


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

Installation

The recommended way to install Geocoder is throughComposer:

$ composer require willdurand/geocoder

Usage

Geocoder and its companionGeocoder Extra provides a lotofproviders.

Choose the one that fits your need first. Let's say theGoogleMaps one is whatyou were looking for, so let's see how to use it. In the code snippet below,curl has been choosen asHTTP layer but it is up to yousince each HTTP-based provider implementsPSR-7.

$curl     =new \Ivory\HttpAdapter\CurlHttpAdapter();$geocoder =new \Geocoder\Provider\GoogleMaps($curl);$geocoder->geocode(...);$geocoder->reverse(...);

TheGeocoder interface, which all providers implement, exposes two mainmethods:

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

It also contains methods to control the number of results:

  • limit($limit)
  • getLimit()

Address & AddressCollection

Bothgeocode() andreverse() methods return a collection ofAddressobjects (AddressCollection), each providing the following API:

  • getCoordinates() will return aCoordinates object (withlatitude andlongitude properties);
  • getLatitude() will return thelatitude value;
  • getLongitude() will return thelongitude value;
  • getBounds() will return anBounds object (withsouth,west,northandeast properties);
  • getStreetNumber() will return thestreet number/house number value;
  • getStreetName() will return thestreet name value;
  • getLocality() will return thelocality orcity;
  • getPostalCode() will return thepostalCode orzipcode;
  • getSubLocality() will return thecity district, orsublocality;
  • getAdminLevels() will return an ordered collection (AdminLevelCollection)ofAdminLevel object (withlevel,name andcode properties);
  • getCountry() will return aCountry object (withname andcodeproperties);
  • getCountryCode() will return the ISOcountry code;
  • getTimezone() will return thetimezone.

TheAddressCollection exposes the following methods:

  • count() (this class implementsCountable);
  • first() retrieves the firstAddress;
  • slice($offset, $length = null) returnsAddress objects between$offsetandlength;
  • get($index) fetches anAddress using its$index;
  • all() returns allAddress objects;
  • getIterator() (this class implementsIteratorAggregate).

The ProviderAggregator

TheProviderAggregator is used to register several providers so that you candecide 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);

TheProviderAggregator'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')    ;

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

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

TimedGeocoder

TheTimedGeocoder class profiles eachgeocode andreverse call. So you caneasily figure out how many time/memory was spent for each geocoder/reverse call.

// configure you geocoder object$stopwatch =new \Symfony\Component\Stopwatch\Stopwatch();$geocoder =new \Geocoder\TimedGeocoder($geocoder,$stopwatch);$geocoder->geocode('Paris, France');// Now you can debug your application

We use thesymfony/stopwatchcomponent under the hood. Which means, if you use the Symfony framework thegeocoder calls will appear in your timeline section in the Web Profiler.

HTTP Adapters

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

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

Note: not all providers are HTTP-based.

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

ProviderNameReverse?SSL?CoverageMultiple?Terms
ArcGIS Onlinearcgis_onlineyessupportedworldwideyesrequires API key. 1250 requests free
Bing Mapsbing_mapsyesnoworldwideyesrequires API key. Limit 10,000 requests per month
Chainchainmeta provider which iterates over a list of providers
Geonamesgeonamesyesnoworldwideyesrequires registration, no free tier
Google Mapsgoogle_mapsyessupportedworldwideyesrequires API key. Limit 2500 requests per day
Google Maps for Businessgoogle_maps_businessyessupportedworldwideyesrequires API key. Limit 100,000 requests per day
MapQuestmap_questyesnoworldwideyesboth open andcommercial service require API key
Nominatimnominatimyessupportedworldwideyesrequires a domain name (e.g. local installation)
OpenCageopencageyessupportedworldwideyesrequires API key. 2500 requests/day free
OpenStreetMapopenstreetmapyesnoworldwideyesheavy users (>1q/s) get banned
TomTomtomtomyesrequiredworldwideyesrequires API key. First 2500 requests or 30 days free
Yandexyandexyesnoworldwideyes

Below, you will find more information for these providers.

ArcGISOnline

It is possible to specify asourceCountry to restrict result to this specificcountry thus reducing request time (note that this doesn't work on reversegeocoding).

GeoIP2

It requires either thedatabasefile, or thewebservice - represented bythe GeoIP2 , which is injected to theGeoIP2Adapter. Thegeoip2/geoip2 package must beinstalled.

This provider will only work with the correspondingGeoIP2Adapter:

<?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')->first();
GoogleMaps

Locale and/or region can be specified:

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

A validClient ID is required. The private key is optional. This provider alsosupports SSL, and extends theGoogleMaps provider.

MaxMindBinary

This provider requires a data file, and thegeoip/geoip package must beinstalled.

It is worth mentioning that this provider hasserious performance issues,and shouldnot be used in production. For more information, please readissue #301.

Nominatim

Access to a Nominatim server is required. See theNominatim WikiPage for more information.

TomTom

The default langage-locale isen, you can choose betweende,es,fr,it,nl,pl,pt andsv.

Yandex

The default language-locale isru-RU, you can choose betweenuk-UA,be-BY,en-US,en-BR andtr-TR. This provider can also reverse information basedon coordinates (latitude, longitude). It's possible to precise the toponym toget more accurate result for reverse geocoding:house,street,metro,district andlocality.

IP-based Providers

ProviderNameIPv4?IPv6?Multiple?TermsNotes
FreeGeoIpfree_geo_ipyesyesno
GeoIPsgeo_ipsyesnonorequires API key
GeoIP2 (Maxmind)maxmind_geoip2yesyesno
GeoPlugingeo_pluginyes yesno
HostIphost_ipyesnono
IpInfoDBip_info_dbyesnonorequires API keycity precision
Geoipgeoipyesnonowrapper around thePHP extension which must be installed
MaxMind web servicemaxmindyesyesnorequires Omni API keyCity/ISP/Org and Omni services, IPv6 on country level
MaxMind Binary filemaxmind_binaryyesnononeeds locally installed database files

Important: theGeocoderExtra library contains evenmore official providers!

Locale Aware Providers

Providers that arelocale aware expose the following methods:

$geocoder->setLocale('xyz');$locale =$geocoder->getLocale();

The Chain Provider

TheChain provider is a special provider that takes a list of providers anditerates over this list to get information. Note that itstops its iterationwhen a provider returns a result. The result is returned byGoogleMaps becauseFreeGeoIp andHostIp 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 anAddress object instandard formats.

GPS eXchange Format (GPX)

TheGPS eXchange format is designed to share geolocated data like point ofinterests, tracks, ways, but also coordinates.Geocoder provides a dumper toconvert anAddress 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:

<gpxversion="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">    <boundsminlat="2.388911"minlon="48.863151"maxlat="2.388911"maxlon="48.863151"/>    <wptlat="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 geographicdata structures.

Keyhole Markup Language (KML)

Keyhole Markup Languageis an XML notation for expressing geographic annotation and visualization withinInternet-based, two-dimensional maps and three-dimensional Earth browsers.

Well-Known Binary (WKB)

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

Well-Known Text (WKT)

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

Formatters

A common use case is to print geocoded data. Thanks to theStringFormatterclass, it's simple to format anAddress 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

  • Admin Level Name:%A1,%A2,%A3,%A4,%A5

  • Admin Level Code:%a1,%a2,%a3,%a4,%a5

  • Country:%C

  • Country Code:%c

  • Timezone:%T

Extending Things

You can write your ownprovider by implementing theProvider interface.

You can provide your owndumper by implementing theDumper interface.

Versioning

Geocoder followsSemantic Versioning.

End Of Life

1.x

As of December 2014, branch1.7 is not officially supported anymore, meaningmajor version1 reached end of life. Last version is:1.7.1.

2.x

As of December 2014, version2.xis in afeature frozen state. All new features should be contributed to version 3.0and upper. Last version is:2.8.1.

Major version2 will reachend of life on December 2015.

Stable Version

Version3.x is the current major stable version of Geocoder.

Contributing

SeeCONTRIBUTINGfile.

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 someskipped unit tests due to the need of API keys.

Rename thephpunit.xml.dist file tophpunit.xml, then uncomment thefollowing 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_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

Contributor Code of Conduct

As contributors and maintainers of this project, we pledge to respect all peoplewho contribute through reporting issues, posting feature requests, updatingdocumentation, submitting pull requests or patches, and other activities.

We are committed to making participation in this project a harassment-freeexperience for everyone, regardless of level of experience, gender, genderidentity and expression, sexual orientation, disability, personal appearance,body size, race, age, or religion.

Examples of unacceptable behavior by participants include the use of sexuallanguage or imagery, derogatory comments or personal attacks, trolling, publicor private harassment, insults, or other unprofessional conduct.

Project maintainers have the right and responsibility to remove, edit, or rejectcomments, commits, code, wiki edits, issues, and other contributions that arenot aligned to this Code of Conduct. Project maintainers who do not follow theCode of Conduct may be removed from the project team.

Instances of abusive, harassing, or otherwise unacceptable behavior may bereported by opening an issue or contacting one or more of the projectmaintainers.

This Code of Conduct is adapted from theContributorCovenant, version 1.0.0, available athttp://contributor-covenant.org/version/1/0/0/

License

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

About

The most featured Geocoder library written in PHP.

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published

Languages

  • PHP100.0%

[8]ページ先頭

©2009-2025 Movatter.jp