PHP
Mapricot's API is plain HTTPS and JSON, so PHP's curl extension covers it, with no Composer package to install. This page calls each API: geocoding, places, routing, and IP geolocation, and shows where the free map tiles fit. It was tested with PHP 8.3, and works with PHP 8.1 and later.
Set up
Create a server key in the dashboard with the products you'll use: Places for geocoding and places, Routing, and IP geolocation. Set it as an environment variable, so it stays out of your code:
export MAPRICOT_KEY="mapricot_sk_…"
Then add a function that sends the key with every request, retries when the API is busy, and throws on errors. It sends a POST when there's a body, and returns the response as an array:
<?php
function mapricot(string $path, array $params = [], ?array $body = null): array
{
$url = 'https://api.mapricot.com' . $path . ($params ? '?' . http_build_query($params) : '');
$headers = ['Authorization: Bearer ' . getenv('MAPRICOT_KEY')];
for ($attempt = 1; ; $attempt++) {
$curl = curl_init($url);
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => $body === null ? $headers : [...$headers, 'Content-Type: application/json'],
]);
if ($body !== null) {
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($body));
}
$response = curl_exec($curl);
if ($response === false) {
throw new RuntimeException(curl_error($curl));
}
$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
if (($status === 429 || $status === 503) && $attempt < 4) {
sleep(2 ** $attempt);
continue;
}
$json = json_decode($response, true, flags: JSON_THROW_ON_ERROR);
if ($status >= 400) {
throw new RuntimeException("Mapricot returned $status: {$json['error']['message']}");
}
return $json;
}
}
Geocode an address
/v1/search turns an address or place name into coordinates:
$data = mapricot('/v1/search', ['q' => '128 SW 3rd Ave, Portland', 'limit' => 1]);
foreach ($data['results'] as $result) {
echo "{$result['label']} {$result['lat']} {$result['lon']}\n";
}
128 SW 3rd Avenue, Portland, OR, USA 45.521736 -122.673276
Each result also has its address in parts under address, and a type, such as address, street, or locality, that says how exact the match is. To limit results to some countries, add 'country' => 'US,CA'. Geocoding lists every parameter and field.
Find the address at a point
/v1/reverse turns coordinates into the nearest address:
$nearest = mapricot('/v1/reverse', ['lat' => 45.5217, 'lon' => -122.6733, 'limit' => 1])['results'][0];
echo "{$nearest['label']} {$nearest['distanceMeters']}\n";
128 SW 3rd Avenue, Portland, OR, USA 4
Suggest places as someone types
/v1/autocomplete takes the text typed so far. focus ranks results near a point first:
$suggestion = mapricot('/v1/autocomplete', ['q' => 'stumpt', 'focus' => '45.52,-122.68', 'limit' => 1])['results'][0];
echo "{$suggestion['label']} {$suggestion['id']}\n";
Stumptown Coffee Roasters, Portland, OR, USA mp_b3BlbnN0cmVldG1hcDp2ZW51ZTpub2RlLzExOTg2MjI2NjYw
Find places nearby
/v1/nearby lists places of a category around a point, nearest first:
$data = mapricot('/v1/nearby', ['lat' => 45.52, 'lon' => -122.68, 'category' => 'food:coffee_shop', 'radius' => 1000, 'limit' => 1]);
foreach ($data['results'] as $place) {
echo "{$place['name']} {$place['distanceMeters']}\n";
}
Public Domain 37
Look up a place by ID
Every result has an id. Save it, and /v1/places/{id} fetches that place again later:
$place = mapricot('/v1/places/' . $suggestion['id'])['result'];
echo "{$place['label']}\n";
Stumptown Coffee Roasters, Portland, OR, USA
Get a route
/v1/route takes a JSON body with two to 20 waypoints and a mode of drive, walk, or bicycle:
$route = mapricot('/v1/route', body: [
'waypoints' => [['lat' => 43.7396, 'lon' => 7.4275], ['lat' => 43.734, 'lon' => 7.4222]],
'mode' => 'walk',
])['routes'][0];
echo "{$route['distanceMeters']} {$route['durationSeconds']}\n";
1044 739
Distances are in meters and times in seconds. When no path connects the waypoints, routes is empty. The route's line is in polyline, encoded with six decimal places, so decode it with precision 6, as decoding a route polyline explains.
Look up an IP address
/v1/ip/{ip} gives the approximate location of an IPv4 or IPv6 address:
$location = mapricot('/v1/ip/8.8.8.8');
echo "{$location['city']} {$location['countryCode']}\n";
Mountain View US
Show a map
Map tiles are free and need no key. MapLibre GL JS draws them in the browser from https://tiles.mapricot.com/styles/light.json, so PHP doesn't fetch them: put your results in the page, and draw them there, as Map tiles shows. MapLibre takes coordinates as [lon, lat].
Errors and retries
mapricot throws a RuntimeException for any error response, with the status and the API's message:
try {
mapricot('/v1/search', ['q' => '']);
} catch (RuntimeException $error) {
echo $error->getMessage(), "\n";
}
Mapricot returned 400: The service rejected the request.
It retries 429 and 503 responses up to three times, waiting 2, 4, then 8 seconds. Errors aren't billed, so retrying them costs nothing. A 429 that keeps coming back can also mean the account is out of credit. Each account has a limit on requests in progress at once, so send requests one at a time or a few at once. The API reference lists every status.