The official PHP client for the My Geocode API: forward and reverse geocoding, address autocomplete, IPv4 and IPv6 lookup, timezones, elevation and postal codes.
- Works on every PHP release from 7.0 to 8.6, with no warnings, notices or deprecations on any of them.
- No dependencies. It uses ext-curl when it is there and PHP's own HTTPS streams when it is not.
- Safe to drop into any project: everything lives in the
MyGeocode\namespace. It defines no global functions, constants or polyfills, and it never touches your ini settings, error handlers, timezone or locale. - 2,500 free requests a day without a key or an account.
composer require mygeocode/mygeocodeWithout Composer, download the source from
github.com/mygeocode/mygeocode-php and point an autoloader at src/:
spl_autoload_register(function ($class) {
if (strpos($class, 'MyGeocode\\') === 0) {
$file = '/path/to/mygeocode-php/src/' . str_replace('\\', '/', substr($class, 10)) . '.php';
if (is_file($file)) {
require $file;
}
}
});<?php
require 'vendor/autoload.php';
$client = new MyGeocode\Client();
$found = $client->forward('Brandenburg Gate, Berlin');
$place = $found->results[0];
echo $place->formatted, "\n"; // Brandenburg Gate, State of Berlin, Germany
echo $place->lat, ', ', $place->lon, "\n"; // 52.516268, 13.377692
$address = $client->reverse(48.8584, 2.2945);
echo $address->result->formatted, "\n"; // 5 Avenue Anatole France, 75007 Paris, FranceWithout a key, each network gets 2,500 free requests a day. $found->meta->quotaFreeRemaining tells you how many are
left.
A key adds your account's prepaid credit or Unlimited package on top of the free requests. Create one in the dashboard.
$client = new MyGeocode\Client(['key' => 'YOUR_KEY']);If you leave out key, the client reads the MYGEOCODE_KEY environment variable. Pass 'key' => '' to make sure no
key is sent. The key always travels in the X-API-Key header, never in the URL, and the SDK never writes it anywhere.
Results are in English unless you set lang. Set it once on the client, or per call:
$client = new MyGeocode\Client(['lang' => 'de']);
$client->reverse(48.8584, 2.2945, ['lang' => 'fr']); // this call onlylang takes an ISO 639-1 code such as de, ja or pt-BR. The whole address comes back in that language and
script. On its own, the API answers each result in the language of its area; the SDK sends lang=en by default so
that every result reads the same.
Every method takes its main arguments first, then an optional array of options. Option names are the API's own
parameter names (only place_id is written placeId). An option the method does not know throws an
InvalidArgumentException, so typos show up straight away. Every method also accepts params, an array of extra query
parameters that are sent as they are, and pretty (bool) for indented JSON.
| Method | Endpoint |
|---|---|
forward |
GET /v1/forward |
reverse |
GET /v1/reverse |
autocomplete |
GET /v1/autocomplete |
ip, ipv4, ipv6 |
GET /v1/ip, /v1/ipv4, /v1/ipv6 |
timezone |
GET /v1/timezone |
elevation |
GET /v1/elevation |
postcode |
GET /v1/postcode |
forwardBatch |
POST /v1/forward |
reverseBatch |
POST /v1/reverse |
ipBatch, ipv4Batch, ipv6Batch |
GET /v1/ip, /v1/ipv4, /v1/ipv6 with ips |
timezoneBatch |
GET /v1/timezone with locations |
elevationBatch |
POST /v1/elevation |
Text, structured address fields or a place id to coordinates. Returns a ForwardResult whose results holds up to
limit Place objects, best first. An empty list means nothing matched.
$client->forward('Brandenburg Gate, Berlin');
$client->forward('Brandenburg Gate, Berlin', ['limit' => 3, 'countries' => ['de']]);
$client->forward(null, ['street' => '10 Downing Street', 'city' => 'London', 'country' => 'GB']);| Option | Type | What it does |
|---|---|---|
street, city, state, postcode, country |
string | Structured search instead of (or as well as) free text. |
placeId |
string | Look up a place_id from an earlier result. |
limit |
int | 1 to 10 results. |
countries |
string or list | ISO 3166-1 alpha-2 codes to search in, such as ['de', 'at']. |
bounds |
string or list | south,west,north,east box that results should fall in. |
strict |
bool | Only return results inside bounds. |
proximity |
string or list | lat,lon to prefer results near. |
types |
string or list | Kinds of result to keep, such as address or poi. |
lang |
string | Language of the result. |
timezone, elevation, wikidata, country_info, codes, sun, regions, districts, census, demographics, road, site |
bool | Each adds its extra block to every result. |
annotations |
bool | Adds every extra block at once. |
A point to the nearest address. Returns a ReverseResult whose result is a Place, or null when nothing is in
range.
$address = $client->reverse(48.8584, 2.2945);
echo $address->result->formatted; // 5 Avenue Anatole France, 75007 Paris, France
echo $address->result->distance_m; // 47 (metres from the point you gave)
$client->reverse(48.8584, 2.2945, ['level' => 'city', 'timezone' => true]);| Option | Type | What it does |
|---|---|---|
level |
string | address, street, postcode, city, region or country. |
radius |
int | Search radius in metres, 1 to 5000. |
lang |
string | Language of the result. |
boundaries |
bool | Add the administrative boundaries the point falls in (Australia). |
the extra-block flags and annotations |
bool | As for forward. |
Suggestions while someone types an address. Returns an AutocompleteResult with a suggestions list; each
Suggestion has text, lat, lon, type, precision and place_id.
$typed = $client->autocomplete('1600 Pennsylvania');
echo $typed->suggestions[0]->text; // 1600 Pennsylvania Avenue NW, Washington, DC 20500, United States
$client->autocomplete('1600 Pennsylvania', ['limit' => 5, 'countries' => 'us']);Options: limit, countries, proximity, bounds, strict, types and lang, as for forward.
Country, region, city, coordinates, timezone, network owner (ASN) and proxy, VPN and data centre flags for an IP
address. ip takes either version; ipv4 and ipv6 accept only their own. Without an address you get the address the
request came from. Returns an IpInfo.
$google = $client->ip('8.8.8.8');
echo $google->country, ', ', $google->city; // United States, Mountain View
echo $google->asn, ' ', $google->as_name; // 15169 Google LLC
var_dump($google->is_datacenter); // bool(true)
$client->ipv6('2001:4860:4860::8888');
$client->ip(); // the address the request came from
$client->ipv4('8.8.8.8', ['elevation' => true]); // adds elevation_mOption: elevation (bool). The full list of IpInfo fields is under Results and meta.
The IANA zone, UTC offset, daylight saving state and local time for a point, now or at a given moment. Returns a
TimezoneResult.
$tokyo = $client->timezone(35.6762, 139.6503);
echo $tokyo->timezone, ' ', $tokyo->utc_offset; // Asia/Tokyo +09:00
echo $tokyo->name, ' (', $tokyo->abbreviation, ')'; // Japan Standard Time (JST)
echo $tokyo->local_time; // 2026-11-24T18:07:15+09:00
$client->timezone(35.6762, 139.6503, ['timestamp' => 1767225600]);
$client->timezone(null, null, ['tz' => 'Europe/Paris']);| Option | Type | What it does |
|---|---|---|
tz |
string | Look up a zone by its IANA or Windows id instead of a point (pass null for lat and lon). |
timestamp |
int | Unix time to answer for. Default: now. |
lang |
string | Language of the zone name. Sent as the API's language parameter, only when you set it here or on the client. language works as another name for this option. |
locations |
list or string | Several points: [[lat, lon], ...], "lat,lon|lat,lon" or an enc: polyline. |
path, samples |
list or string, int | Points along a path, sampled samples times (2 to 100). |
bounds, rows, cols |
string or list, int, int | A grid of points over a box. |
For a plain list of points, timezoneBatch is simpler.
Height in metres above sea level (negative for the sea floor), from a global 15 arc-second grid. Returns an
ElevationResult whose results holds ElevationPoint objects with lat, lon, elevation_m and resolution_m.
$everest = $client->elevation(27.9881, 86.9250);
echo $everest->results[0]->elevation_m; // 8627| Option | Type | What it does |
|---|---|---|
locations |
list or string | Several points (pass null for lat and lon). |
path, samples |
list or string, int | Heights along a path. |
bounds, rows, cols |
string or list, int, int | Heights over a grid. |
A postal code to its place, region and coordinates. Returns a PostcodeResult whose results lists every place that
uses the code.
$nyc = $client->postcode('10001', ['country' => 'US']);
$first = $nyc->results[0];
echo $first->place, ', ', $first->region_code; // New York, NY
echo $first->lat, ', ', $first->lon; // 40.748401, -73.996702
$client->postcode('75008', ['country' => 'FR']);Option: country (ISO alpha-2). Without it, the code is matched in every country.
Up to 100 searches in one request (each counts as one request against your quota). Returns a ForwardBatchResult
whose results holds one ForwardBatchEntry per search, in the order you sent them; each entry has the query and
its own results list of Place objects.
$batch = $client->forwardBatch(['Brandenburg Gate, Berlin', 'Sydney Opera House', 'Statue of Liberty, New York']);
foreach ($batch->results as $entry) {
echo $entry->query, ': ', $entry->results[0]->formatted, "\n";
}
// Brandenburg Gate, Berlin: Brandenburg Gate, State of Berlin, Germany
// Sydney Opera House: Sydney Opera House, Sydney, New South Wales, Australia
// Statue of Liberty, New York: Statue of Liberty, New York, New York, United States
$client->forwardBatch(['Brandenburg Gate, Berlin', 'Sydney Opera House'], ['limit' => 1, 'timezone' => true]);The options apply to every search in the batch:
| Option | Type | What it does |
|---|---|---|
limit |
int | 1 to 10 results per search. |
countries, bounds, strict, proximity, types |
as for forward |
Filters for every search. |
lang |
string | Language of the results. |
timezone, elevation, wikidata, country_info, codes, sun, regions, districts, census, demographics, road, site |
bool | Each adds its extra block to every result. |
annotations |
bool | Adds every extra block at once. |
Structured fields and placeId are not available in a batch; use forward for those.
Up to 100 points in one request (each counts as one request). Returns a ReverseBatchResult whose results holds
one ReverseResult per point, in the order you sent them; its result is a Place, or null when nothing is in
range.
$batch = $client->reverseBatch([[48.8584, 2.2945], [40.6892, -74.0445], [-33.8568, 151.2153]]);
foreach ($batch->results as $point) {
echo $point->result ? $point->result->formatted : 'nothing in range', "\n";
}
// 5 Avenue Anatole France, 75007 Paris, France
// 1 Liberty Island, New York, NY 10004, United States
// 2B Macquarie Street, Sydney NSW 2000, AustraliaThe options apply to every point in the batch:
| Option | Type | What it does |
|---|---|---|
level |
string | address, street, postcode, city, region or country. |
radius |
int | Search radius in metres, 1 to 5000. |
lang |
string | Language of the results. |
boundaries |
bool | Add the administrative boundaries each point falls in (Australia). |
the extra-block flags and annotations |
bool | As for forward. |
Up to 100 addresses in one request. ipBatch takes both versions mixed; ipv4Batch and ipv6Batch accept only
their own. Returns an IpBatchResult whose results holds one IpInfo per address, in the order you sent them. An
address the API cannot read gets an entry whose status is error and whose error explains why, while the rest
still answer.
$batch = $client->ipv4Batch(['8.8.8.8', '1.1.1.1', '9.9.9.9']);
foreach ($batch->results as $info) {
echo $info->ip, ': ', $info->status === 'ok' ? $info->as_name : $info->error['message'], "\n";
}
// 8.8.8.8: Google LLC
// 1.1.1.1: Cloudflare, Inc.
// 9.9.9.9: Quad9
$client->ipv6Batch(['2001:4860:4860::8888', '2606:4700:4700::1111']);
$client->ipBatch(['8.8.8.8', '2606:4700:4700::1111'], ['elevation' => true]);Option: elevation (bool), adds elevation_m to every address.
Timezones for up to 100 points. Returns a TimezoneBatchResult whose results holds one TimezoneResult per point,
in the order you sent them.
$batch = $client->timezoneBatch([[48.8584, 2.2945], [40.6892, -74.0445], [-33.8568, 151.2153]]);
foreach ($batch->results as $zone) {
echo $zone->timezone, "\n";
}
// Europe/Paris
// America/New_York
// Australia/SydneyOptions: timestamp (Unix time, default now) and lang (also accepted as language), as for timezone.
Heights for up to 100 points, sent as a POST body. Returns an ElevationResult.
$batch = $client->elevationBatch([[48.8584, 2.2945], [40.6892, -74.0445], [-33.8568, 151.2153]]);
foreach ($batch->results as $point) {
echo $point->elevation_m, "\n";
}
// 37
// 0
// 10Results are plain objects whose properties carry the API's own field names, so the API documentation describes them field by field:
$place = $client->forward('Brandenburg Gate, Berlin')->results[0];
$place->formatted; // "Brandenburg Gate, State of Berlin, Germany"
$place->precision; // "house"
$place->components->city; // address parts: road, house_number, postcode, city, state, country ...
$place->components->country_code; // "de"A field the API did not send is null, so check for null before you use one. The fields this SDK reads are never
renamed or removed from the API: if one ever has to go, it keeps coming back with the value null, and your code keeps
working. A list that comes back null reads as an empty list. Every result object also has raw, the decoded JSON as
an array, so fields added to the API later are readable before the SDK knows them.
What each method returns, and the properties you can read:
| Class | Returned by | Properties |
|---|---|---|
ForwardResult |
forward |
status, query, results (list of Place), meta, raw |
ReverseResult |
reverse, each entry of reverseBatch |
status, lat, lon, result (Place or null), meta, raw |
Place |
inside forward and reverse results | formatted, lat, lon, type, precision, confidence, place_id, components, bounds, distance_m, formatted_place, place, parcel, codes, population, timezone, elevation_m, raw |
Components |
Place::$components |
poi, building, unit, level, house_number, road, lot, suburb, municipality, city, county, state, state_code, postcode, country, country_code, official_name, raw |
Bounds |
Place::$bounds |
north, south, east, west |
AutocompleteResult |
autocomplete |
status, query, suggestions (list of Suggestion), meta, raw |
Suggestion |
inside autocomplete results | text, lat, lon, type, precision, place_id, raw |
IpInfo |
ip, ipv4, ipv6, each entry of the IP batches |
status, ip, version, found, prefix, country, country_code, continent, continent_code, region, region_code, city, postcode, lat, lon, elevation_m, timezone, utc_offset, utc_offset_seconds, is_eu, asn, as_name, org, usage_type, registry, allocated, tags, is_anycast, is_satellite, is_datacenter, is_proxy, is_vpn_provider, is_tor, crawler, is_private, reason, abuse_email, threat, updated_at, error, meta, raw |
TimezoneResult |
timezone, each entry of timezoneBatch |
status, lat, lon, timezone, name, abbreviation, utc_offset, utc_offset_seconds, raw_offset_seconds, dst, dst_offset_seconds, timestamp, local_time, country_code, is_ocean, windows_timezone, next_transition, meta, raw |
ElevationResult |
elevation, elevationBatch |
status, results (list of ElevationPoint), meta, raw |
ElevationPoint |
inside elevation results | lat, lon, elevation_m, resolution_m, raw |
PostcodeResult |
postcode |
status, postcode, country_code, results (list of PostcodePlace), meta, raw |
PostcodePlace |
inside postcode results | postcode, place, region, region_code, country, country_code, lat, lon, raw |
ForwardBatchResult |
forwardBatch |
status, results (list of ForwardBatchEntry), meta, raw |
ForwardBatchEntry |
inside forward batch results | query, results (list of Place), raw |
ReverseBatchResult |
reverseBatch |
status, results (list of ReverseResult), meta, raw |
IpBatchResult |
ipBatch, ipv4Batch, ipv6Batch |
status, results (list of IpInfo), meta, raw |
TimezoneBatchResult |
timezoneBatch |
status, results (list of TimezoneResult), meta, raw |
The extra blocks you ask for with the flags (timezone, elevation, wikidata and the rest) are on Place where
the SDK knows them (timezone, elevation_m, codes, population) and always in $place->raw.
Every response object has meta, filled from the response headers:
| Property | Header | Meaning |
|---|---|---|
requestId |
X-Request-Id |
Quote it when you contact support. |
quotaLimit |
X-Quota-Limit |
Free requests a day for this key's account or network. |
quotaUsed |
X-Quota-Used |
Free requests used today. |
quotaFreeRemaining |
X-Quota-Free-Remaining |
Free requests left today. |
quotaReset |
X-Quota-Reset |
Unix time when the free requests reset. |
creditsRemaining |
X-Credits-Remaining |
Prepaid credit left, when a key with credit is used. |
Everything the SDK throws extends MyGeocode\MyGeocodeError (itself a RuntimeException):
| Class | When |
|---|---|
MyGeocode\ApiError |
The API answered with an error. status is the HTTP status, code the API's error code (such as invalid_request, invalid_key or quota_exceeded), message its explanation, param the parameter at fault, requestId and retryAfter (seconds, or null). |
MyGeocode\RequestTimeoutError |
No answer within timeout. |
MyGeocode\NetworkError |
The connection failed: DNS, refused, TLS. |
MyGeocode\DecodeError |
The answer could not be read as JSON. |
use MyGeocode\ApiError;
use MyGeocode\MyGeocodeError;
try {
$client->forward('Brandenburg Gate, Berlin');
} catch (ApiError $e) {
echo $e->status, ' ', $e->code, ': ', $e->message;
} catch (MyGeocodeError $e) {
echo 'Could not reach the API: ', $e->getMessage();
}The errors page lists every error code.
The client retries on its own, up to maxRetries times (default 2):
- 429 (too many requests): waits for
Retry-After, or untilX-Quota-Reset. If that is longer thanmaxRetryWait(default 60 seconds), for example when the day's free requests are gone, it throws theApiErrorstraight away instead of waiting. - 500: tries once more after one second.
- 503: waits for
Retry-After, or 1, 2 and then 4 seconds. - Timeouts and connection errors: retried with the same 1, 2, 4 second pattern for GET requests. The POST batch calls are not retried after a connection error, so a batch is never charged twice.
Other errors are thrown at once.
All options are optional:
$client = new MyGeocode\Client([
'key' => 'YOUR_KEY', // default: MYGEOCODE_KEY, else no key
'baseUrl' => 'https://api.mygeocode.com/v1',
'timeout' => 10, // seconds per request
'maxRetries' => 2,
'maxRetryWait' => 60, // seconds
'lang' => 'en',
'transport' => new MyGeocode\Transport\StreamTransport(), // default: CurlTransport when ext-curl is loaded
]);sleep and clock replace the wait and the clock the retry logic uses. They are meant for tests, see below.
The client sends every request through a MyGeocode\Transport\Transport. Give it your own to test code that uses the
SDK without touching the network:
use MyGeocode\Transport\Response;
use MyGeocode\Transport\Transport;
class CannedTransport implements Transport
{
public function send($method, $url, array $headers, $body, $timeout)
{
return new Response(200, ['Content-Type' => 'application/json'], json_encode([
'status' => 'ok',
'lat' => 48.8584,
'lon' => 2.2945,
'result' => ['formatted' => '5 Avenue Anatole France, 75007 Paris, France', 'lat' => 48.858821, 'lon' => 2.294596],
]));
}
}
$client = new MyGeocode\Client([
'transport' => new CannedTransport(),
'sleep' => function ($seconds) {}, // no real waiting in retry tests
]);The same interface plugs in any HTTP library. This adapter uses a PSR-18 client such as Guzzle or Symfony HttpClient, without the SDK needing any PSR package itself (set the timeout on your PSR-18 client):
use MyGeocode\Transport\Response;
use MyGeocode\Transport\Transport;
use MyGeocode\Transport\TransportException;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Client\NetworkExceptionInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;
class Psr18Transport implements Transport
{
private $http;
private $requests;
private $streams;
public function __construct(ClientInterface $http, RequestFactoryInterface $requests, StreamFactoryInterface $streams)
{
$this->http = $http;
$this->requests = $requests;
$this->streams = $streams;
}
public function send($method, $url, array $headers, $body, $timeout)
{
$request = $this->requests->createRequest($method, $url);
foreach ($headers as $name => $value) {
$request = $request->withHeader($name, $value);
}
if ($body !== null) {
$request = $request->withBody($this->streams->createStream($body));
}
try {
$response = $this->http->sendRequest($request);
} catch (NetworkExceptionInterface $e) {
throw new TransportException($e->getMessage(), 0, $e);
}
return new Response($response->getStatusCode(), $response->getHeaders(), (string) $response->getBody());
}
}Throw MyGeocode\Transport\TimeoutException for a timeout and TransportException for any other failure; the client
turns them into RequestTimeoutError and NetworkError.
The tests need nothing but PHP, so the same suite runs on every version from 7.0 up. It answers from real recorded API responses and never calls the API:
composer test
# or, without Composer
php tests/run.phpAny warning, notice or deprecation counts as a failed test.
- PHP 7.0 or newer. Tested on 7.0, 7.1, 7.2, 7.3, 7.4, 8.0, 8.1, 8.2, 8.3, 8.4, 8.5, 8.6 and the current development branch, with every warning and deprecation treated as a failure.
- ext-json (built into PHP 8 and enabled by default in PHP 7).
- ext-curl, or ext-openssl for PHP's own HTTPS streams. Almost every PHP install has both.
- API documentation
- Pricing and free tier
- Dashboard and API keys
- Issues
- Support: support@mygeocode.com
MIT. See LICENSE.