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

sshilko/Geocoder

 
 

Repository files navigation

Build StatusTotal DownloadsLatest Stable Version

Geocoder is a library which helps you build geo-aware applications. Itprovides an abstraction layer for geocoding manipulations.

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 requires theegeloen/http-adapter library.

Providers

Providers contain the logic to extract useful information.

Currently, there are many providers for the following APIs:

Address-based geocoding

providerreverseSSLcoverageterms
Google Mapsyesnoworldwiderequires API key. Limit 2500 requests per day
Google Maps for Businessyesnoworldwiderequires API key. Limit 100,000 requests per day
Bing Mapsyesnoworldwiderequires API key. Limit 10,000 requests per month.
OpenStreetMapyesnoworldwideheavy users (>1q/s) get banned
Nominatimyessupportedworldwiderequires a domain name (e.g. local installation)
MapQuestyesnoworldwideboth open andcommercial service require API key
OpenCageyessupportedworldwiderequires API key. 2500 requests/day free
Yandexyesnoworldwide
Geonamesyesnoworldwiderequires registration, no free tier
TomTomyesrequiredworldwiderequires API key. First 2500 requests or 30 days free
ArcGIS Onlineyessupportedworldwiderequires API key. 1250 requests free
Chainmeta provider which iterates over a list of providers

IP-based geocoding

providerIPv6termsnotes
FreeGeoIpyes
HostIpno
IpInfoDBnocity precision
Geoip?wrapper around thePHP extension
GeoPluginyes
GeoIPsnorequires API key
MaxMind web serviceyesrequires Omni API keyCity/ISP/Org and Omni services, IPv6 on country level
MaxMind binary fileyesneeds locally installed database files
MaxMindGeoIP2yes

TheGeocoder Extra library contains even more providers!

Installation

The recommended way to install Geocoder is throughComposer.

Create acomposer.json file into your project:

{"require": {"willdurand/geocoder":"@stable"    }}

Protip: you should browse thewilldurand/geocoder pageto choose a stable version to use, avoid the@stable meta constraint.

And run these two commands to install it:

$ curl -sS https://getcomposer.org/installer| php$ composer install

You're done.

Usage

First, you need anadapter to query an API:

<?php$adapter  =new \Geocoder\HttpAdapter\BuzzHttpAdapter();

TheBuzzHttpAdapter is tweakable, actually you can pass aBrowser object to this adapter:

<?php$buzz    =new \Buzz\Browser(new \Buzz\Client\Curl());$adapter =new \Geocoder\HttpAdapter\BuzzHttpAdapter($buzz);

Now, you have to choose aprovider which is closed to what you want to get.

FreeGeoIp

TheFreeGeoIp namedfree_geo_ip is able to geocodeIPv4 and IPv6addresses only.

HostIp

TheHostIp namedhost_ip is able to geocodeIPv4 addresses only.

IpInfoDb

TheIpInfoDb namedip_info_db is able to geocodeIPv4 addressesonly. A valid api key is required.

GoogleMaps

TheGoogleMaps namedgoogle_maps is able to geocode and reversegeocodestreet addresses. A locale and a region can be set as well as anoptional api key. This provider also supports SSL.

GoogleMapsBusiness

TheGoogleMapsBusiness namedgoogle_maps_business is able to geocodeand reverse geocodestreet addresses. A validClient ID is required. Theprivate key is optional. This provider also supports SSL.

BingMaps

TheBingMaps namedbing_maps is able to geocode and reverse geocodestreet addresses. A valid api key is required.

OpenStreetMap

TheOpenStreetMap namedopenstreetmap is able to geocode and reversegeocodestreet addresses.

Nominatim

TheNominatim namednominatim is able to geocode and reverse geocodestreet addresses. Access to a Nominatim server is required. See theNominatim Wiki Page for moreinformation.

Geoip

TheGeoip namedgeoip is able to geocodeIPv4 and IPv6 addressesonly. No need to use anHttpAdapter as it uses a local database. See theMaxMind page for more information.

Chain

TheChain namedchain is a special provider that takes a list ofproviders and iterates over this list to get information.

MapQuest

TheMapQuest namedmap_quest is able to geocode and reverse geocodestreet addresses. A valid api key is required. Access toMapQuest'slicensedendpointsis provided via constructor argument.

OpenCage

TheOpenCage namedopencage is able to geocode and reverse geocodestreet addresses. A valid api key is required.

Yandex

TheYandex namedyandex is able to geocode and reverse geocodestreet addresses. The default language-locale isru-RU, you can choosebetweenuk-UA,be-BY,en-US,en-BR andtr-TR. This provider can alsoreverse information based on coordinates (latitude, longitude). It's possible toprecise the toponym to get more accurate result for reverse geocoding:house,street,metro,district andlocality.

GeoPlugin

TheGeoPlugin namedgeo_plugin is able to geocodeIPv4 addressesand IPv6 addresses only.

GeoIPs

TheGeoIPs namedgeo_ips is able to geocodeIPv4 addresses only.A valid api key is required.

MaxMind

TheMaxMind namedmaxmind is able to geocodeIPv4 and IPv6addresses only. A validCity/ISP/Org orOmni service's api key isrequired. This provider provides two constantsCITY_EXTENDED_SERVICE bydefault andOMNI_SERVICE.

MaxMindBinary

TheMaxMindBinary namedmaxmind_binary is able to geocodeIPv4 andIPv6 addresses only. It 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.

GeoIP2Database

TheGeoIP2 namedmaxmind_geoip2 is able to geocodeIPv4 and IPv6addresses only - it makes use of the MaxMind GeoIP2 databases or thewebservice.

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.

Usage
<?php// Maxmind GeoIP2 Provider: e.g. the database reader$reader   =new \GeoIp2\Database\Reader('/path/to/database');$adapter  =new \Geocoder\HttpAdapter\GeoIP2Adapter($reader);$provider =new \Geocoder\Provider\GeoIP2($adapter);$geocoder =new \Geocoder\Geocoder($provider);$address   =$geocoder->geocode('74.200.247.59');

Geonames

TheGeonames namedgeonames is able to geocode and reverse geocodeplaces. A valid username is required.

TomTom

TheTomTom namedtomtom is able to geocode and reverse geocodestreet addresses. The default langage-locale isen, you can choosebetweende,es,fr,it,nl,pl,pt andsv. A valid api key isrequired.

ArcGISOnline

TheArcGISOnline namedarcgis_online is able to geocode and reversegeocodestreet addresses. It's possible to specify a sourceCountry torestrict result to this specific country thus reducing request time (note thatthis doesn't work on reverse geocoding). This provider also supports SSL.

Using The Providers

You can use one of them or write your own provider. You can also register allproviders and decide later. That's we'll do:

<?php$geocoder =new \Geocoder\ProviderBasedGeocoder();$geocoder->registerProviders(array(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    ),new \Geocoder\Provider\Nominatim($adapter,'http://your.nominatim.server',$locale    ),));

Parameters:

  • $locale is available forYandex,BingMaps,OpenCage andTomTom
  • $region is available forGoogleMaps andGoogleMapsBusiness
  • $toponym is available forYandex
  • $service is available forMaxMind
  • $useSsl is available forGoogleMaps,GoogleMapsBusiness,OpenCage,MaxMind andArcGISOnline
  • $sourceCountry is available forArcGISOnline
  • $rootUrl is available forNominatim

Using The Chain Provider

As said it's a special provider that takes a list of providers and iterates overthis list to get information. Note that itstops its iteration when aprovider returns a result. The result is returned byGoogleMaps becauseFreeGeoIp andHostIp cannot geocode street addresses.BingMaps is ignored.

$geocoder =new \Geocoder\ProviderBasedGeocoder();$adapter  =new \Geocoder\HttpAdapter\CurlHttpAdapter();$chain    =new \Geocoder\Provider\Chain(array(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!

API

The main method is calledgeocode() which receives a value to geocode. It canbe an IP address or a street address (partial or not).

<?php$address =$geocoder->geocode('88.188.221.14');// Result is:// "latitude"       => string(9) "47.901428"// "longitude"      => string(8) "1.904960"// "bounds"         => array(4) {//     "south" => string(9) "47.813320"//     "west"  => string(8) "1.809770"//     "north" => string(9) "47.960220"//     "east"  => string(8) "1.993860"// }// "streetNumber"   => string(0) ""// "streetName"     => string(0) ""// "cityDistrict"   => string(0) ""// "city"           => string(7) "Orleans"// "zipcode"        => string(0) ""// "county"         => string(6) "Loiret"// "countyCode"     => null// "region"         => string(6) "Centre"// "regionCode"     => null// "country"        => string(6) "France"// "countryCode"    => string(2) "FR"// "timezone"       => string(6) "Europe/Paris"$address =$geocoder->geocode('10 rue Gambetta, Paris, France');// Result is:// "latitude"       => string(9) "48.863217"// "longitude"      => string(8) "2.388821"// "bounds"         => array(4) {//     "south" => string(9) "48.863217"//     "west"  => string(8) "2.388821"//     "north" => string(9) "48.863217"//     "east"  => string(8) "2.388821"// }// "streetNumber"   => string(2) "10"// "streetName"     => string(15) "Avenue Gambetta"// "cityDistrict"   => string(18) "20E Arrondissement"// "city"           => string(5) "Paris"// "county"         => string(5) "Paris"// "countyCode"     => null// "zipcode"        => string(5) "75020"// "region"         => string(14) "Ile-de-France"// "regionCode"     => null// "country"        => string(6) "France"// "countryCode"    => string(2) "FR"// "timezone"       => string(6) "Europe/Paris"

Thegeocode() method returns an array ofAddress objects, each providing thefollowing 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;
  • getCounty() will return aCounty object (withname andcodeproperties);
  • getCountyCode() will return thecounty code (county short name);
  • getRegion() will return aRegion object (withname andcodeproperties);
  • getRegionCode() will return theregion code (region short name);
  • getCountry() will return aCountry object (withname andcodeproperties);
  • getCountryCode() will return the ISOcountry code;
  • getTimezone() will return thetimezone.

TheProviderBasedGeocoder's API is fluent, you can write:

<?php$address =$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.

Reverse Geocoding

This library provides areverse() method to retrieve information fromcoordinates:

$address =$geocoder->reverse($latitude,$longitude);

Dumpers

Geocoder provides dumpers that aim to transform anAddress object in standard 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

  • County:%P

  • County Code:%p

  • Region:%R

  • Region Code:%r

  • 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.

Contributing

SeeCONTRIBUTINGfile.

Unit Tests

To run unit tests, you'll needcURL and a set of dependencies you can installusing Composer:

composer install --dev

Once installed, 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_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.

About

The most featured Geocoder library written in PHP.

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp