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 almost missing Geocoder PHP library.

License

NotificationsYou must be signed in to change notification settings

snc/Geocoder

 
 

Repository files navigation

Geocoder is a library which helps you build geo-aware applications. It provides an abstraction layer for geocoding manipulations.The library is split in two parts:HttpAdapter andProvider and is really extensible.

Build Status

HttpAdapters

HttpAdapters are responsible to get data from remote APIs.

Currently, there are the following adapters:

  • BuzzHttpAdapter to useBuzz, a lightweight PHP 5.3 library for issuing HTTP requests;
  • CurlHttpAdapter to usecURL;
  • GuzzleHttpAdapter to useGuzzle, PHP 5.3+ HTTP client and framework for building RESTful web service clients;
  • SocketHttpAdapter to use asocket;
  • ZendHttpAdapter to useZend Http Client.

Providers

Providers contain the logic to extract useful information.

Currently, there are many providers for the following APIs:

  • FreeGeoIp as IP-Based geocoding provider;
  • HostIp as IP-Based geocoding provider;
  • IpInfoDB as IP-Based geocoding provider (city precision);
  • Google Maps as Address-Based geocoding and reverse geocoding provider;
  • Google Maps for Business as Address-Based geocoding and reverse geocoding provider;
  • Bing Maps as Address-Based geocoding and reverse geocoding provider;
  • OpenStreetMap as Address-Based geocoding and reverse geocoding provider (based on the Nominatim provider);
  • Nominatim as Address-Based geocoding and reverse geocoding provider;
  • CloudMade as Address-Based geocoding and reverse geocoding provider;
  • Geoip, the PHP extension, as IP-Based geocoding provider;
  • ChainProvider is a special provider that takes a list of providers and iteratesover this list to get information;
  • MapQuest as Address-Based geocoding and reverse geocoding provider;
  • OIORest as very accurate Address-Based geocoding and reverse geocoding provider (exclusively in Denmark);
  • GeoCoder.ca as Address-Based geocoding and reverse geocoding provider (exclusively in USA & Canada);
  • GeoCoder.us as Address-Based geocoding provider (exclusively in USA);
  • IGN OpenLS as Address-Based geocoding provider (exclusively in France);
  • DataScienceToolkit as IP-Based geocoding provider or an Address-Based provider (exclusively in USA & Canada);
  • Yandex as Address-Based geocoding and reverse geocoding provider;
  • GeoPlugin as IP-Based geocoding provider;
  • GeoIPs as IP-Based geocoding provider;
  • MaxMind web service as IP-Based geocoding provider (City/ISP/Org and Omni services);
  • MaxMind binary file as IP-Based geocoding provider;
  • Geonames as Place-Based geocoding and reverse geocoding provider;
  • IpGeoBase as IP-Based geocoding provider (very accurate in Russia);
  • Baidu as Address-Based geocoding and reverse geocoding provider (exclusively in China);
  • TomTom as Address-Based geocoding and reverse geocoding provider;
  • ArcGIS Online as Address-Based geocoding and reverse geocoding provider.

TheGeocoder Extra library contains even more providers!

Installation

The recommended way to install Geocoder is through composer.

Just create acomposer.json file for your project:

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

Protip: you should browse thewilldurand/geocoderpage to 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

Now you can add the autoloader, and you will have access to the library:

<?phprequire'vendor/autoload.php';

If you don't use eitherComposer or aClassLoader in your application, just require the provided autoloader:

<?phprequire_once'src/autoload.php';

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.

FreeGeoIpProvider

TheFreeGeoIpProvider namedfree_geo_ip is able to geocodeIPv4 and IPv6 addresses only.

HostIpProvider

TheHostIpProvider namedhost_ip is able to geocodeIPv4 addresses only.

IpInfoDbProvider

TheIpInfoDbProvider namedip_info_db is able to geocodeIPv4 addresses only.A valid api key is required.

GoogleMapsProvider

TheGoogleMapsProvider namedgoogle_maps is able to geocode and reverse geocodestreet addresses.

GoogleMapsBusinessProvider

TheGoogleMapsBusinessProvider namedgoogle_maps_business is able to geocode and reverse geocodestreet addresses.A validClient ID is required. The private key is optional.

BingMapsProvider

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

OpenStreetMapProvider

TheOpenStreetMapProvider namedopenstreetmap is able to geocode and reversegeocodestreet addresses.

Warning: TheOpenStreetMapsProvider isdeprecated, and you shouldrather use theOpenStreetMapProvider. See issue#269.

NominatimProvider

TheNominatimProvider namednominatim is able to geocode and reverse geocodestreet addresses.Access to a Nominatim server is required. See theNominatimWiki Page for more information.

CloudMadeProvider

TheCloudMadeProvider namedcloudmade is able to geocode and reverse geocodestreet addresses.A valid api key is required.

GeoipProvider

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

ChainProvider

TheChainProvider namedchain is a special provider that takes a list of providers and iterates over this list to get information.

MapQuestProvider

TheMapQuestProvider namedmap_quest is able to geocode and reverse geocodestreet addresses.A valid api key is required.

OIORestProvider

TheOIORestProvider namedoio_rest is able to geocode and reverse geocodestreet addresses, exclusively in Denmark.

GeocoderCaProvider

TheGeocoderCaProvider namedgeocoder_ca is able to geocode and reverse geocodestreet addresses, exclusively in USA & Canada.

GeocoderUsProvider

TheGeocoderUsProvider namedgeocoder_us is able to geocodestreet addresses only, exclusively in USA.

IGNOpenLSProvider

TheIGNOpenLSProvider namedign_openls is able to geocodestreet addresses only, exclusively in France.A valid OpenLS api key is required.

DataScienceToolkitProvider

TheDataScienceToolkitProvider nameddata_science_toolkit is able to geocodeIPv4 addresses andstreet adresses, exclusively in USA & Canada.

YandexProvider

TheYandexProvider namedyandex is able to geocode and reverse geocodestreet addresses.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 based on coordinates (latitude,longitude). It's possible to precise the toponym to get more accurate result for reverse geocoding:house,street,metro,district andlocality.

GeoPluginProvider

TheGeoPluginProvider namedgeo_plugin is able to geocodeIPv4 addresses and IPv6 addresses only.

GeoIPsProvider

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

MaxMindProvider

TheMaxMindProvider namedmaxmind is able to geocodeIPv4 and IPv6 addresses only.A validCity/ISP/Org orOmni service's api key is required.This provider provides two constantsCITY_EXTENDED_SERVICE by default andOMNI_SERVICE.

GeonamesProvider

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

IpGeoBaseProvider

TheIpGeoBaseProvider namedip_geo_base is able to geocodeIPv4 addresses only, very accurate in Russia.

BaiduProvider

TheBaiduProvider namedbaidu is able to geocode and reverse geocodestreet addresses, exclusively in China.A valid api key is required.

TomTomProvider

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

ArcGISOnlineProvider

TheArcGISOnlineProvider namedarcgis_online is able to geocode and reverse geocodestreet addresses.It's possible to specify a sourceCountry to restrict result to this specific country thus reducingrequest time (note that this 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 all providers and decide later.That's we'll do:

<?php$geocoder =new \Geocoder\Geocoder();$geocoder->registerProviders(array(new \Geocoder\Provider\GoogleMapsProvider($adapter,$locale,$region,$useSsl    ),new \Geocoder\Provider\GoogleMapsBusinessProvider($adapter,'<CLIENT_ID>','<PRIVATE_KEY>',$locale,$region,$useSsl    ),new \Geocoder\Provider\YandexProvider($adapter,$locale,$toponym    ),new \Geocoder\Provider\MaxMindProvider($adapter,'<MAXMIND_API_KEY>',$service,$useSsl    ),new \Geocoder\Provider\ArcGISOnlineProvider($adapter,$sourceCountry,$useSsl    ),new \Geocoder\Provider\NominatimProvider($adapter,'http://your.nominatim.server',$locale    ),));

Parameters:

  • $locale is available forYandexProvider,BingMapsProvider andTomTomProvider.
  • $region is available forGoogleMapsProvider andGoogleMapsBusinessProvider.
  • $toponym is available forYandexProvider.
  • $service is available forMaxMindProvider.
  • $useSsl is available forGoogleMapsProvider,GoogleMapsBusinessProvider,MaxMindProvider andArcGISOnlineProvider.
  • $sourceCountry is available forArcGISOnlineProvider.
  • $rootUrl is available forNominatimProvider.

Using The ChainProvider

As said it's a special provider that takes a list of providers and iterates over this list to get information. Notethat itstops its iteration when a provider returns a result. The result is returned byGoogleMapsProviderbecauseFreeGeoIpProvider andHostIpProvider cannot geocode street addresses.BingMapsProvider is ignored.

$geocoder =new \Geocoder\Geocoder();$adapter  =new \Geocoder\HttpAdapter\CurlHttpAdapter();$chain    =new \Geocoder\Provider\ChainProvider(array(new \Geocoder\Provider\FreeGeoIpProvider($adapter),new \Geocoder\Provider\HostIpProvider($adapter),new \Geocoder\Provider\GoogleMapsProvider($adapter,'fr_FR','France',true),new \Geocoder\Provider\BingMapsProvider($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 can be an IP address or a street address (partial or not).

<?php$result =$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"$result =$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 aGeocoded result object with the following API, this object also implements theArrayAccess interface:

  • getCoordinates() will return an array withlatitude andlongitude values;
  • getLatitude() will return thelatitude value;
  • getLongitude() will return thelongitude value;
  • getBounds() will return an array withsouth,west,north andeast values;
  • getStreetNumber() will return thestreet number/house number value;
  • getStreetName() will return thestreet name value;
  • getCity() will return thecity;
  • getZipcode() will return thezipcode;
  • getCityDistrict() will return thecity district, orsublocality;
  • getCounty() will return thecounty;
  • getCountyCode() will return thecounty code (county short name);
  • getRegion() will return theregion;
  • getRegionCode() will return theregion code (region short name);
  • getCountry() will return thecountry;
  • getCountryCode() will return the ISOcountry code;
  • getTimezone() will return thetimezone.

The Geocoder's API is fluent, you can write:

<?php$result =$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.The default behavior is to use the first one but it can be annoying.

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

Reverse Geocoding

This library provides areverse() method to retrieve information from coordinates:

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

Dumpers

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

GPS eXchange Format (GPX)

TheGPS eXchange format is designed to share geolocated data like point of interests, tracks, ways, but alsocoordinates.Geocoder provides a dumper to convert aResultInterface object in an GPX compliant format.

Assuming we got a$result object as seen previously:

<?php$dumper =new \Geocoder\Dumper\GpxDumper();$strGpx =$dumper->dump($result);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 geographic data structures.

Keyhole Markup Language (KML)

Keyhole Markup Language is an XML notationfor expressing geographic annotation and visualization within Internet-based, two-dimensional mapsand 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.

Formatter

A common use case is to print geocoded data. Thanks to theFormatter class,it's really easy to format aResultInterface object as a string:

<?php// $result is an instance of ResultInterface$formatter =new \Geocoder\Formatter\Formatter($result);$formatter->format('%S %n, %z %L');// 'Badenerstrasse 120, 8001 Zuerich'$formatter->format('<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 provide your ownadapter, you just need to create a new class which implementsHttpAdapterInterface.

You can also write your ownprovider by implementing theProviderInterface.

You can provide your ownresult by extendingDefaultResultFactory orMultipleResultFactory and implementingResultInterface if your provider returns one or multiple results and more informations than the default one.Please note that the methodcreateFromArray is markedfinal in these factories.

If you need your ownResultFactory, just implementResultFactoryInterface.

Note,AbstractProvider andAbstractResult classes can help you by providing useful features.

You can provide your owndumper by implementing theDumperInterface.

Write your ownformatter by implementing theFormatterInterface.

Contributing

See CONTRIBUTING file.

Unit Tests

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

composer install --dev

Once installed, just launch 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 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="CLOUDMADE_API_KEY" value="YOUR_API_KEY" />--><!-- <server name="IGN_WEB_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="BAIDU_API_KEY" value="YOUR_API_KEY" />--><!-- <server name="TOMTOM_GEOCODING_KEY" value="YOUR_GEOCODING_KEY" />--><!-- <server name="TOMTOM_MAP_KEY" value="YOUR_MAP_KEY" />--></php>

You're done.

Credits

License

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

About

The almost missing Geocoder PHP library.

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published

Languages

  • PHP100.0%

[8]ページ先頭

©2009-2025 Movatter.jp