Help us shape the future of Go! Take the 2026 Go Developer Survey

mapbox

package module
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 29, 2026 License: MIT Imports: 15 Imported by: 0

README

mapbox-go

Go client for the Mapbox APIs.

Supported endpoints

API Endpoint
Map Matching v5 POST /matching/v5/{profile}
Geocoding v6 Reverse GET /search/geocode/v6/reverse
Geocoding v6 Batch POST /search/geocode/v6/batch
Search Box Suggest GET /search/searchbox/v1/suggest
Search Box Retrieve GET /search/searchbox/v1/retrieve/{mapbox_id}

Installation

go get github.com/way-platform/mapbox-go

Usage

client := mapbox.NewClient(
    mapbox.WithAccessToken(os.Getenv("MAPBOX_ACCESS_TOKEN")),
)

// Map Matching
resp, err := client.MapMatch(ctx, &mapbox.MapMatchRequest{
    Coordinates: []mapbox.Coordinate{
        {Longitude: 13.418946, Latitude: 52.500217},
        {Longitude: 13.419946, Latitude: 52.501217},
    },
    Radiuses:   []float64{25.0, 25.0},   // meters
    Timestamps: []float64{1700000000, 1700000010}, // Unix seconds
})
if err != nil {
    log.Fatal(err)
}
if !resp.Code.IsSuccess() {
    // Handle NoMatch / NoSegment per your degradation policy.
    log.Printf("no match: %s", resp.Code)
}

// Reverse geocode
fc, err := client.ReverseGeocode(ctx, &mapbox.ReverseGeocodeRequest{
    Longitude: 13.405,
    Latitude:  52.52,
})

// Batch reverse geocode (up to 1000 per request)
results, err := client.BatchReverseGeocode(ctx, &mapbox.BatchReverseGeocodeRequest{
    Queries: []mapbox.ReverseGeocodeQuery{
        {Longitude: 13.405, Latitude: 52.52},
        {Longitude: -0.1278, Latitude: 51.5074},
    },
})

Observability

Inject a custom http.RoundTripper via WithTransport to observe all API calls without adding any vendor-specific code to this SDK:

client := mapbox.NewClient(
    mapbox.WithAccessToken(token),
    mapbox.WithTransport(myMetricsTransport),
)

The transport sees every outbound request after auth (?access_token=) is injected.

Retries

Retry is disabled by default. Enable with WithRetryCount:

client := mapbox.NewClient(
    mapbox.WithAccessToken(token),
    mapbox.WithRetryCount(3), // retries on 429 and 5xx
)

Error handling

HTTP errors return *mapbox.Error. Use the helper functions:

_, err := client.MapMatch(ctx, req)
if mapbox.IsRateLimited(err) { ... }
if mapbox.IsUnauthorized(err) { ... }

Map Matching semantic failures (no route found) are not Go errors. Check resp.Code:

if !resp.Code.IsSuccess() {
    // resp.Code is CodeNoMatch or CodeNoSegment
}

CLI

# Install
go install github.com/way-platform/mapbox-go/cmd/mapbox@latest

# Save credentials
mapbox auth login --token $MAPBOX_ACCESS_TOKEN

# Map match
mapbox map-match --input coords.json

# Reverse geocode
mapbox geocode --lon 13.405 --lat 52.52

# Batch reverse geocode
mapbox geocode-batch --input coords.json

Documentation

Overview

Package mapbox provides a Go client for the Mapbox APIs.

Supported endpoints:

  • Map Matching v5: POST /matching/v5/{profile}
  • Geocoding v6 Reverse: GET /search/geocode/v6/reverse
  • Geocoding v6 Batch: POST /search/geocode/v6/batch

Authentication uses the Mapbox access token passed via WithAccessToken. The token is appended as an ?access_token= query parameter on every request.

To instrument API calls (e.g. for metrics), inject a custom http.RoundTripper via WithTransport. The SDK layers auth and retry on top of the provided transport.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsForbidden

func IsForbidden(err error) bool

IsForbidden reports whether err is a 403 Mapbox API error.

func IsInvalidInput

func IsInvalidInput(err error) bool

IsInvalidInput reports whether err is a 422 Mapbox API error.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound reports whether err is a 404 Mapbox API error.

func IsRateLimited

func IsRateLimited(err error) bool

IsRateLimited reports whether err is a 429 Mapbox API error.

func IsServerError

func IsServerError(err error) bool

IsServerError reports whether err is a 5xx Mapbox API error.

func IsUnauthorized

func IsUnauthorized(err error) bool

IsUnauthorized reports whether err is a 401 Mapbox API error.

Types

type AddressContext

type AddressContext struct {
	// MapboxID is the unique Mapbox identifier.
	MapboxID string `json:"mapbox_id"`
	// AddressNumber is the building/house number.
	AddressNumber string `json:"address_number"`
	// StreetName is the street name.
	StreetName string `json:"street_name"`
}

AddressContext contains the street-level address components.

type BatchReverseGeocodeRequest

type BatchReverseGeocodeRequest struct {
	// Queries are the coordinates to reverse geocode. Must contain 1–1000 items.
	Queries []ReverseGeocodeQuery
}

BatchReverseGeocodeRequest is the request for Geocoding v6 Batch.

type BoundingBox

type BoundingBox struct {
	MinLongitude float64
	MinLatitude  float64
	MaxLongitude float64
	MaxLatitude  float64
}

BoundingBox is a geographic bounding box.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a client for the Mapbox APIs.

func NewClient

func NewClient(opts ...Option) *Client

NewClient creates a new Mapbox API client. At minimum, supply WithAccessToken.

func (*Client) BatchReverseGeocode

func (c *Client) BatchReverseGeocode(ctx context.Context, req *BatchReverseGeocodeRequest) (_ []*FeatureCollection, err error)

BatchReverseGeocode performs a batch reverse geocode lookup using Geocoding v6 Batch. Returns one *FeatureCollection per input query, in the same order. Up to 1,000 queries per request.

func (*Client) MapMatch

func (c *Client) MapMatch(ctx context.Context, req *MapMatchRequest) (_ *MapMatchResponse, err error)

MapMatch submits GPS coordinates to the Mapbox Map Matching API.

A successful HTTP response with Code "NoMatch" or "NoSegment" is returned as (response, nil) — these are not Go errors. Callers should inspect response.Code and implement a degradation policy as needed (e.g. fall back to the raw input path when Code is not Ok or Confidence < 0.5).

HTTP 4xx/5xx responses are returned as *Error.

func (*Client) Retrieve

func (c *Client) Retrieve(ctx context.Context, req *RetrieveRequest) (_ *RetrieveResponse, err error)

Retrieve resolves a suggestion to a full place record including coordinates. The SessionToken must match the one used in the preceding Suggest call.

func (*Client) ReverseGeocode

func (c *Client) ReverseGeocode(ctx context.Context, req *ReverseGeocodeRequest) (_ *FeatureCollection, err error)

ReverseGeocode performs a single reverse geocode lookup using Geocoding v6.

func (*Client) Suggest

func (c *Client) Suggest(ctx context.Context, req *SuggestRequest) (_ *SuggestResponse, err error)

Suggest performs a Search Box /suggest call, returning autocomplete suggestions for the given query. Use the same SessionToken for the paired Retrieve call.

type Code

type Code string

Code is a Mapbox API response code. It appears in two places:

Use CodeOf to extract the code from any error.

const (
	// CodeUnknown is the zero value, returned by [CodeOf] when the error has no code.
	CodeUnknown Code = ""
	// CodeOK indicates a successful Map Matching result.
	CodeOK Code = "Ok"
	// CodeNoMatch indicates no route matched the input trace.
	CodeNoMatch Code = "NoMatch"
	// CodeNoSegment indicates no road was found within the provided radiuses.
	CodeNoSegment Code = "NoSegment"
	// CodeTooManyCoordinates indicates more than 100 coordinates were provided.
	CodeTooManyCoordinates Code = "TooManyCoordinates"
	// CodeInvalidInput indicates a malformed request.
	CodeInvalidInput Code = "InvalidInput"
	// CodeProfileNotFound indicates an invalid routing profile was specified.
	CodeProfileNotFound Code = "ProfileNotFound"
)

func CodeOf

func CodeOf(err error) Code

CodeOf returns the Mapbox API response code from err, or CodeUnknown if err is nil, is not a Mapbox error, or the error body contained no code field.

Use this to switch on specific error codes:

switch mapbox.CodeOf(err) {
case mapbox.CodeTooManyCoordinates:
    // split and retry
case mapbox.CodeInvalidInput:
    // log and discard
}

func (Code) IsSuccess

func (c Code) IsSuccess() bool

IsSuccess reports whether the code represents a successful Map Matching result.

type ContextItem

type ContextItem struct {
	// MapboxID is the unique Mapbox identifier.
	MapboxID string `json:"mapbox_id"`
	// Name is the display name for this context level.
	Name string `json:"name"`
}

ContextItem is a single named level in the address hierarchy.

type Coordinate

type Coordinate struct {
	// Longitude is the east-west position in decimal degrees.
	Longitude float64
	// Latitude is the north-south position in decimal degrees.
	Latitude float64
}

Coordinate is a geographic coordinate with longitude and latitude.

type CountryContext

type CountryContext struct {
	// MapboxID is the unique Mapbox identifier.
	MapboxID string `json:"mapbox_id"`
	// Name is the country name.
	Name string `json:"name"`
	// CountryCode is the ISO 3166-1 alpha-2 country code (e.g. "DE").
	CountryCode string `json:"country_code,omitempty"`
	// CountryCodeAlpha3 is the ISO 3166-1 alpha-3 country code (e.g. "DEU").
	CountryCodeAlpha3 string `json:"country_code_alpha_3,omitempty"`
}

CountryContext is the country level in the address hierarchy.

type Error

type Error struct {
	// StatusCode is the HTTP status code.
	StatusCode int
	// Status is the HTTP status text (e.g. "422 Unprocessable Entity").
	Status string
	// Message is the human-readable error message parsed from the Mapbox JSON
	// response body (the "message" field). Empty if the body was not valid JSON
	// or did not contain a message field.
	Message string
	// Body is the raw response body, kept for debugging.
	Body string
	// contains filtered or unexported fields
}

Error represents an HTTP-level error response from the Mapbox API. Use errors.As to unwrap, or CodeOf to extract the response code.

func (*Error) Code

func (e *Error) Code() Code

Code returns the Mapbox API response code parsed from the error body, or CodeUnknown if the body did not contain a code field.

func (*Error) Error

func (e *Error) Error() string

type Feature

type Feature struct {
	Type       string            `json:"type"`
	ID         string            `json:"id"`
	Geometry   GeoJSONGeometry   `json:"geometry"`
	Properties FeatureProperties `json:"properties"`
}

Feature is a GeoJSON Feature with Mapbox v6 geocoding properties.

type FeatureCollection

type FeatureCollection struct {
	Type     string    `json:"type"`
	Features []Feature `json:"features"`
}

FeatureCollection is a GeoJSON FeatureCollection returned by Geocoding v6.

type FeatureContext

type FeatureContext struct {
	Address      *AddressContext `json:"address,omitempty"`
	Street       *ContextItem    `json:"street,omitempty"`
	Neighborhood *ContextItem    `json:"neighborhood,omitempty"`
	Postcode     *ContextItem    `json:"postcode,omitempty"`
	Locality     *ContextItem    `json:"locality,omitempty"`
	Place        *ContextItem    `json:"place,omitempty"`
	District     *ContextItem    `json:"district,omitempty"`
	Region       *RegionContext  `json:"region,omitempty"`
	Country      *CountryContext `json:"country,omitempty"`
}

FeatureContext contains the hierarchical address components from Mapbox v6. All fields are optional pointers — nil indicates the component is not present for this feature.

type FeatureProperties

type FeatureProperties struct {
	// MapboxID is the unique Mapbox identifier for this feature.
	MapboxID string `json:"mapbox_id"`
	// FeatureType is the type of feature (e.g. "address", "place", "region").
	FeatureType string `json:"feature_type"`
	// Name is the primary name of the feature.
	Name string `json:"name"`
	// PlaceFormatted is the place portion of the full address.
	PlaceFormatted string `json:"place_formatted,omitempty"`
	// FullAddress is the full formatted address string.
	FullAddress string `json:"full_address,omitempty"`
	// Context contains the hierarchical address components.
	Context FeatureContext `json:"context"`
}

FeatureProperties contains the Mapbox v6 geocoding result properties.

type GeoJSONGeometry

type GeoJSONGeometry struct {
	Type        string `json:"type"`
	Coordinates any    `json:"coordinates"`
}

GeoJSONGeometry is a GeoJSON geometry object.

type MapMatchRequest

type MapMatchRequest struct {
	// Profile is the Mapbox routing profile.
	// Accepted values: "mapbox/driving", "mapbox/walking", "mapbox/cycling",
	// "mapbox/driving-traffic". Defaults to "mapbox/driving" if empty.
	Profile string
	// Coordinates is the sequence of GPS coordinates to match.
	// Must contain between 2 and 100 coordinates.
	Coordinates []Coordinate
	// Radiuses is the per-coordinate uncertainty radius in meters (0–50).
	// If provided, must have the same length as Coordinates.
	// 25m is a reasonable starting value for fleet GPS noise tolerance.
	Radiuses []float64
	// Timestamps is the per-coordinate Unix timestamp in seconds.
	// If provided, must have the same length as Coordinates and be in
	// ascending order. Highly recommended by Mapbox for quality matching.
	Timestamps []float64
}

MapMatchRequest is the request for the Mapbox Map Matching API v5.

type MapMatchResponse

type MapMatchResponse struct {
	// Code is the Mapbox response code. Check Code.IsSuccess() for a successful match.
	// HTTP 200 is returned for both successful and semantic-failure cases (e.g. NoMatch).
	Code Code `json:"code"`
	// Message contains additional detail, set when Code is not Ok.
	Message string `json:"message,omitempty"`
	// Matchings contains the matched route segments, ordered by confidence descending.
	Matchings []Matching `json:"matchings"`
	// Tracepoints is a per-input-coordinate array. A nil element indicates the
	// corresponding input coordinate could not be matched to a road.
	Tracepoints []*Tracepoint `json:"tracepoints"`
}

MapMatchResponse is the response from the Mapbox Map Matching API.

type Matching

type Matching struct {
	// Confidence is the match quality score in the range [0, 1].
	// Mapbox treats values below 0.5 as low-quality.
	Confidence float64 `json:"confidence"`
	// Geometry is the matched route geometry as a GeoJSON LineString.
	// Nil when overview=false was requested.
	Geometry *GeoJSONGeometry `json:"geometry"`
	// Distance is the matched distance in metres.
	Distance float64 `json:"distance"`
	// Duration is the estimated travel time in seconds.
	Duration float64 `json:"duration"`
}

Matching is a single matched route segment.

type Option

type Option func(*Client)

Option configures a Client.

func WithAccessToken

func WithAccessToken(token string) Option

WithAccessToken sets the Mapbox access token. It is appended as an ?access_token= query parameter on every request.

func WithBaseURL

func WithBaseURL(url string) Option

WithBaseURL overrides the default API base URL. Useful for testing.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient sets a base *http.Client whose Transport is used as the innermost transport in the chain.

func WithRetryCount

func WithRetryCount(n int) Option

WithRetryCount sets the number of additional retry attempts on 429 and 5xx responses. Default is 0 (no retries). The consuming service controls this; the SDK does not retry by default.

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout sets the per-request HTTP timeout. Default is 30s.

func WithTransport

func WithTransport(rt http.RoundTripper) Option

WithTransport sets the base http.RoundTripper, replacing http.DefaultTransport. Use this to inject observability (metrics, tracing) without adding any vendor-specific code to this SDK. The SDK layers auth (token injection) and retry on top of the provided transport so every outbound API call passes through it.

type RegionContext

type RegionContext struct {
	// MapboxID is the unique Mapbox identifier.
	MapboxID string `json:"mapbox_id"`
	// Name is the region name.
	Name string `json:"name"`
	// RegionCode is the ISO 3166-2 region code (e.g. "DE-BY").
	RegionCode string `json:"region_code,omitempty"`
	// RegionCodeFull is the full ISO 3166-2 region code.
	RegionCodeFull string `json:"region_code_full,omitempty"`
}

RegionContext is the region/state/province level in the address hierarchy.

type RetrieveCoordinates

type RetrieveCoordinates struct {
	Longitude float64 `json:"longitude"`
	Latitude  float64 `json:"latitude"`
	// Accuracy describes the precision of the coordinate
	// (e.g. "rooftop", "parcel", "interpolated").
	Accuracy string `json:"accuracy,omitempty"`
}

RetrieveCoordinates contains the resolved coordinate and accuracy from /retrieve.

type RetrieveFeature

type RetrieveFeature struct {
	Type       string                    `json:"type"`
	Geometry   GeoJSONGeometry           `json:"geometry"`
	Properties RetrieveFeatureProperties `json:"properties"`
}

RetrieveFeature is a GeoJSON Feature returned by /retrieve.

type RetrieveFeatureProperties

type RetrieveFeatureProperties struct {
	MapboxID       string              `json:"mapbox_id"`
	FeatureType    string              `json:"feature_type"`
	Name           string              `json:"name"`
	PlaceFormatted string              `json:"place_formatted,omitempty"`
	FullAddress    string              `json:"full_address,omitempty"`
	Coordinates    RetrieveCoordinates `json:"coordinates"`
	Context        FeatureContext      `json:"context"`
}

RetrieveFeatureProperties contains the resolved place details from /retrieve.

type RetrieveRequest

type RetrieveRequest struct {
	// MapboxID is the mapbox_id from a Suggestion (required).
	MapboxID string
	// SessionToken must match the session_token used in the preceding Suggest calls.
	SessionToken string
	// Language is the IETF language tag for the response.
	Language string
}

RetrieveRequest is the request for Search Box /retrieve.

type RetrieveResponse

type RetrieveResponse struct {
	Type        string            `json:"type"`
	Features    []RetrieveFeature `json:"features"`
	Attribution string            `json:"attribution"`
}

RetrieveResponse is the response from Search Box /retrieve.

type ReverseGeocodeQuery

type ReverseGeocodeQuery struct {
	// Longitude is the coordinate to reverse geocode.
	Longitude float64
	// Latitude is the coordinate to reverse geocode.
	Latitude float64
}

ReverseGeocodeQuery is a single query in a batch reverse geocode request.

type ReverseGeocodeRequest

type ReverseGeocodeRequest struct {
	// Longitude is the coordinate to reverse geocode.
	Longitude float64
	// Latitude is the coordinate to reverse geocode.
	Latitude float64
}

ReverseGeocodeRequest is the request for Geocoding v6 Reverse.

type SuggestRequest

type SuggestRequest struct {
	// Query is the search string (required, max 256 chars).
	Query string
	// SessionToken is a UUIDv4 that groups suggest+retrieve calls for billing.
	// The same token must be used across the entire suggest→retrieve sequence.
	// Required.
	SessionToken string
	// Language is the IETF language tag for results (e.g. "en", "de").
	Language string
	// Limit caps the number of suggestions returned (max 10).
	Limit int
	// Proximity biases results toward a coordinate.
	Proximity *Coordinate
	// BBox restricts results to a bounding box.
	BBox *BoundingBox
	// Countries restricts results to a list of ISO 3166 alpha-2 codes.
	Countries []string
	// Types filters results to specific feature types.
	Types []string
}

SuggestRequest is the request for Search Box /suggest.

type SuggestResponse

type SuggestResponse struct {
	Suggestions []*Suggestion `json:"suggestions"`
	Attribution string        `json:"attribution"`
}

SuggestResponse is the response from Search Box /suggest.

type Suggestion

type Suggestion struct {
	// MapboxID is used as the path parameter for /retrieve.
	// Only valid for the duration of the session (180s); do not store it.
	MapboxID       string          `json:"mapbox_id"`
	Name           string          `json:"name"`
	FeatureType    string          `json:"feature_type"`
	PlaceFormatted string          `json:"place_formatted,omitempty"`
	FullAddress    string          `json:"full_address,omitempty"`
	Address        string          `json:"address,omitempty"`
	Language       string          `json:"language,omitempty"`
	Context        *FeatureContext `json:"context,omitempty"`
	POICategory    []string        `json:"poi_category,omitempty"`
	// Distance is meters from the proximity point, if provided.
	Distance *float64 `json:"distance,omitempty"`
}

Suggestion is a single autocomplete suggestion from /suggest.

type Tracepoint

type Tracepoint struct {
	// Location is the snapped coordinate as [longitude, latitude].
	Location []float64 `json:"location"`
	// WaypointIndex is the index of the corresponding waypoint in the matched route.
	WaypointIndex int `json:"waypoint_index"`
	// MatchingsIndex is the index into MapMatchResponse.Matchings that this point belongs to.
	MatchingsIndex int `json:"matchings_index"`
	// AlternativesCount is the number of alternative matches at this point. 0 = unambiguous.
	AlternativesCount int `json:"alternatives_count"`
	// Name is the road name at the snapped location.
	Name string `json:"name"`
}

Tracepoint is a matched input coordinate. Nil tracepoints in MapMatchResponse.Tracepoints indicate coordinates that could not be matched.

Directories

Path Synopsis
Package cli provides credentials management and Cobra commands for the Mapbox API CLI.
Package cli provides credentials management and Cobra commands for the Mapbox API CLI.
cmd
mapbox command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL