Go

Mapricot's API is plain HTTPS and JSON, so Go's standard library covers it, with no module to add. This page calls each API: geocoding, places, routing, and IP geolocation, and shows where the free map tiles fit. It was tested with Go 1.24.

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 returns an error for error responses. It sends a POST when there's a body, and decodes the JSON response into out:

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/url"
	"os"
	"time"
)

var client = &http.Client{Timeout: 30 * time.Second}

func mapricot(path string, params url.Values, body any, out any) error {
	u := "https://api.mapricot.com" + path
	if params != nil {
		u += "?" + params.Encode()
	}
	method, payload := "GET", []byte(nil)
	if body != nil {
		method = "POST"
		var err error
		if payload, err = json.Marshal(body); err != nil {
			return err
		}
	}
	for attempt := 1; ; attempt++ {
		req, err := http.NewRequest(method, u, bytes.NewReader(payload))
		if err != nil {
			return err
		}
		req.Header.Set("Authorization", "Bearer "+os.Getenv("MAPRICOT_KEY"))
		if body != nil {
			req.Header.Set("Content-Type", "application/json")
		}
		resp, err := client.Do(req)
		if err != nil {
			return err
		}
		data, err := io.ReadAll(resp.Body)
		resp.Body.Close()
		if err != nil {
			return err
		}
		if (resp.StatusCode == 429 || resp.StatusCode == 503) && attempt < 4 {
			time.Sleep(time.Duration(1<<attempt) * time.Second)
			continue
		}
		if resp.StatusCode >= 400 {
			var e struct{ Error struct{ Message string } }
			json.Unmarshal(data, &e)
			return fmt.Errorf("mapricot returned %d: %s", resp.StatusCode, e.Error.Message)
		}
		return json.Unmarshal(data, out)
	}
}

Then the types for the fields you use. encoding/json matches field names without regard to case, so DistanceMeters reads distanceMeters:

type Place struct {
	ID, Type, Name, Label string
	Lat, Lon              float64
	DistanceMeters        float64
	Categories            []string
}

type Places struct{ Results []Place }

type Routes struct {
	Routes []struct {
		DistanceMeters, DurationSeconds float64
		Polyline                        string
	}
}

type IPLocation struct{ City, CountryCode string }

The examples below go in func main().

Geocode an address

/v1/search turns an address or place name into coordinates:

var search Places
if err := mapricot("/v1/search", url.Values{"q": {"128 SW 3rd Ave, Portland"}, "limit": {"1"}}, nil, &search); err != nil {
	log.Fatal(err)
}
for _, result := range search.Results {
	fmt.Println(result.Label, result.Lat, result.Lon)
}
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:

var reverse Places
if err := mapricot("/v1/reverse", url.Values{"lat": {"45.5217"}, "lon": {"-122.6733"}, "limit": {"1"}}, nil, &reverse); err != nil {
	log.Fatal(err)
}
fmt.Println(reverse.Results[0].Label, reverse.Results[0].DistanceMeters)
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:

var suggestions Places
if err := mapricot("/v1/autocomplete", url.Values{"q": {"stumpt"}, "focus": {"45.52,-122.68"}, "limit": {"1"}}, nil, &suggestions); err != nil {
	log.Fatal(err)
}
suggestion := suggestions.Results[0]
fmt.Println(suggestion.Label, suggestion.ID)
Stumptown Coffee Roasters, Portland, OR, USA mp_b3BlbnN0cmVldG1hcDp2ZW51ZTpub2RlLzExOTg2MjI2NjYw

Find places nearby

/v1/nearby lists places of a category around a point, nearest first:

var nearby Places
params := url.Values{"lat": {"45.52"}, "lon": {"-122.68"}, "category": {"food:coffee_shop"}, "radius": {"1000"}, "limit": {"1"}}
if err := mapricot("/v1/nearby", params, nil, &nearby); err != nil {
	log.Fatal(err)
}
for _, place := range nearby.Results {
	fmt.Println(place.Name, place.DistanceMeters)
}
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:

var saved struct{ Result Place }
if err := mapricot("/v1/places/"+suggestion.ID, nil, nil, &saved); err != nil {
	log.Fatal(err)
}
fmt.Println(saved.Result.Label)
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:

var route Routes
body := map[string]any{
	"waypoints": []map[string]float64{{"lat": 43.7396, "lon": 7.4275}, {"lat": 43.734, "lon": 7.4222}},
	"mode":      "walk",
}
if err := mapricot("/v1/route", nil, body, &route); err != nil {
	log.Fatal(err)
}
fmt.Println(route.Routes[0].DistanceMeters, route.Routes[0].DurationSeconds)
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:

var location IPLocation
if err := mapricot("/v1/ip/8.8.8.8", nil, nil, &location); err != nil {
	log.Fatal(err)
}
fmt.Println(location.City, location.CountryCode)
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 Go doesn't fetch them: send your results to a web page, and draw them there, as Map tiles shows. MapLibre takes coordinates as [lon, lat].

Errors and retries

mapricot returns an error for any error response, with the status and the API's message:

if err := mapricot("/v1/search", url.Values{"q": {""}}, nil, &search); err != nil {
	fmt.Println(err)
}
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, not from hundreds of goroutines. The API reference lists every status.