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 ¶
- func IsForbidden(err error) bool
- func IsInvalidInput(err error) bool
- func IsNotFound(err error) bool
- func IsRateLimited(err error) bool
- func IsServerError(err error) bool
- func IsUnauthorized(err error) bool
- type AddressContext
- type BatchReverseGeocodeRequest
- type BoundingBox
- type Client
- func (c *Client) BatchReverseGeocode(ctx context.Context, req *BatchReverseGeocodeRequest) (_ []*FeatureCollection, err error)
- func (c *Client) Geocode(ctx context.Context, req *GeocodeRequest) (_ *FeatureCollection, err error)
- func (c *Client) MapMatch(ctx context.Context, req *MapMatchRequest) (_ *MapMatchResponse, err error)
- func (c *Client) Retrieve(ctx context.Context, req *RetrieveRequest) (_ *RetrieveResponse, err error)
- func (c *Client) ReverseGeocode(ctx context.Context, req *ReverseGeocodeRequest) (_ *FeatureCollection, err error)
- func (c *Client) Suggest(ctx context.Context, req *SuggestRequest) (_ *SuggestResponse, err error)
- type Code
- type ContextItem
- type Coordinate
- type CountryContext
- type Error
- type Feature
- type FeatureCollection
- type FeatureContext
- type FeatureProperties
- type GeoJSONGeometry
- type GeocodeRequest
- type Leg
- type LegAnnotation
- type MapMatchRequest
- type MapMatchResponse
- type Matching
- type Option
- type PointGeometry
- type RegionContext
- type RetrieveCoordinates
- type RetrieveFeature
- type RetrieveFeatureProperties
- type RetrieveRequest
- type RetrieveResponse
- type ReverseGeocodeQuery
- type ReverseGeocodeRequest
- type SuggestRequest
- type SuggestResponse
- type Suggestion
- type Tracepoint
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func IsForbidden ¶
IsForbidden reports whether err is a 403 Mapbox API error.
func IsInvalidInput ¶
IsInvalidInput reports whether err is a 422 Mapbox API error.
func IsNotFound ¶
IsNotFound reports whether err is a 404 Mapbox API error.
func IsRateLimited ¶
IsRateLimited reports whether err is a 429 Mapbox API error.
func IsServerError ¶
IsServerError reports whether err is a 5xx Mapbox API error.
func IsUnauthorized ¶
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
// Permanent requests Permanent tier geocoding, which permits storing results.
// Defaults to Temporary tier when false.
Permanent bool
}
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 ¶
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) Geocode ¶ added in v0.4.0
func (c *Client) Geocode(ctx context.Context, req *GeocodeRequest) (_ *FeatureCollection, err error)
Geocode performs a forward geocode lookup using Geocoding v6.
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:
- HTTP 200 Map Matching response bodies (e.g. CodeOK, CodeNoMatch)
- HTTP 4xx error response bodies (e.g. CodeInvalidInput, CodeTooManyCoordinates)
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 ¶
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
}
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 ¶
Code returns the Mapbox API response code parsed from the error body, or CodeUnknown if the body did not contain a code field.
type Feature ¶
type Feature struct {
Type string `json:"type"`
ID string `json:"id"`
Geometry PointGeometry `json:"geometry"`
Properties FeatureProperties `json:"properties"`
}
Feature is a GeoJSON Feature with Mapbox v6 geocoding properties.
type FeatureCollection ¶
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 [][]float64 `json:"coordinates"`
}
GeoJSONGeometry is the GeoJSON LineString geometry returned by the Map Matching API. Each element of Coordinates is a [longitude, latitude] pair, following GeoJSON axis order.
type GeocodeRequest ¶ added in v0.4.0
type GeocodeRequest struct {
// Query is the search text (address, city name, etc.). Required, max 256 chars.
Query string
// Permanent requests Permanent tier geocoding, which permits storing results
// indefinitely. Defaults to Temporary tier when false.
Permanent bool
// Countries restricts results to one or more ISO 3166-1 alpha-2 country codes.
Countries []string
// Types filters results to specific feature types (e.g. "address", "place").
Types []string
// Limit caps the number of results returned (max 10, default 5).
Limit int
// Language is an IETF language tag for result text (e.g. "fi", "en").
Language string
// BBox limits results to a bounding box (minLon,minLat,maxLon,maxLat).
BBox *BoundingBox
// Proximity biases results toward a coordinate.
Proximity *Coordinate
// Autocomplete enables partial-match results. Default true when omitted.
// Set to a non-nil false to disable.
Autocomplete *bool
}
GeocodeRequest is the request for Geocoding v6 Forward.
type Leg ¶ added in v0.3.0
type Leg struct {
// Annotation contains per-segment metadata when annotations are requested.
Annotation *LegAnnotation `json:"annotation,omitempty"`
}
Leg is a route leg between two consecutive waypoints in a matching.
type LegAnnotation ¶ added in v0.3.0
type LegAnnotation struct {
// Duration is the duration in seconds for each geometry segment in the leg.
Duration []float64 `json:"duration,omitempty"`
}
LegAnnotation holds per-geometry-segment metadata for a route leg. The length of each array equals the number of geometry coordinate pairs minus one for this leg (i.e., the number of segments).
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"`
// Legs contains one route leg per consecutive waypoint pair in this matching.
// Present when annotations are requested.
Legs []Leg `json:"legs"`
}
Matching is a single matched route segment.
type Option ¶
type Option func(*Client)
Option configures a Client.
func WithAccessToken ¶
WithAccessToken sets the Mapbox access token. It is appended as an ?access_token= query parameter on every request.
func WithBaseURL ¶
WithBaseURL overrides the default API base URL. Useful for testing.
func WithHTTPClient ¶
WithHTTPClient sets a base *http.Client whose Transport is used as the innermost transport in the chain.
func WithRetryCount ¶
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 ¶
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 PointGeometry ¶ added in v0.2.1
PointGeometry is a GeoJSON Point geometry. Coordinates holds [longitude, latitude].
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 PointGeometry `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
// Permanent requests Permanent tier geocoding, which permits storing results.
// Defaults to Temporary tier when false.
Permanent bool
}
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.