gosrm

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Feb 3, 2024 License: GPL-3.0 Imports: 8 Imported by: 0

README

test code quality coverage

GOSRM


GOSRM is an OSRM client written in Go. It implements all OSRM 5.x installations.
If you want to get the most out of this package I highly recommend to read OSRM docs.

Features


  • Nearest Service
  • Route Service
  • Table Service
  • Match Service
  • Trip Service
  • Tile Service

Installation


Requires Go >= 1.18: go get github.com/mojixcoder/gosrm

How To Use


package main

import (
    "context"
    "fmt"

    "github.com/mojixcoder/gosrm"
)

func main() {
    osrm, err := gosrm.New("http://router.project-osrm.org")
    checkErr(err)
 
    nearestRes, err := gosrm.Nearest(context.Background(), osrm, gosrm.Request{
        Profile:     gosrm.ProfileDriving,
	Coordinates: []gosrm.Coordinate{{13.388860, 52.517037}},
    }, gosrm.WithNumber(3), gosrm.WithBearings([]gosrm.Bearing{{Value: 0, Range: 20}}))
    checkErr(err)

    fmt.Println("### Nearest Response ###")
    fmt.Printf("%#v\n", nearestRes)
    fmt.Println("##########")

    // String type represents the type of geometries returned by OSRM.
    // It can be either string or gosrm.LineString based on geometries option.
    // If you don't specify any geometries the default is polyline and you can use string.
    routeRes, err := gosrm.Route[string](context.Background(), osrm, gosrm.Request{
	Profile:     gosrm.ProfileDriving,
	Coordinates: []gosrm.Coordinate{{13.388860, 52.517037}, {13.397634, 52.529407}, {13.428555, 52.523219}},
    })
    checkErr(err)

    fmt.Println("\n### Route Response ###")
    fmt.Printf("%#v\n", routeRes)
    fmt.Println("##########")

    tableRes, err := gosrm.Table(context.Background(), osrm, gosrm.Request{
	Profile:     gosrm.ProfileDriving,
	Coordinates: []gosrm.Coordinate{{13.388860, 52.517037}, {13.397634, 52.529407}, {13.428555, 52.523219}},
    }, gosrm.WithSources([]uint16{0, 1}), gosrm.WithDestinations([]uint16{2}))
    checkErr(err)

    fmt.Println("\n### Table Response ###")
    fmt.Printf("%#v\n", tableRes)
    fmt.Println("##########")

    // This time we use geojson geometries so geometry type is gosrm.LineString not string.
    matchRes, err := gosrm.Match[gosrm.LineString](context.Background(), osrm, gosrm.Request{
	Profile:     gosrm.ProfileDriving,
	Coordinates: []gosrm.Coordinate{{13.3122, 52.5322}, {13.3065, 52.5283}},
    }, gosrm.WithAnnotations(gosrm.AnnotationsTrue), gosrm.WithGeometries(gosrm.GeometryGeoJSON))
    checkErr(err)

    fmt.Println("\n### Match Response ###")
    fmt.Printf("%#v\n", matchRes)
    fmt.Println("##########")

    tripRes, err := gosrm.Trip[string](context.Background(), osrm, gosrm.Request{
	Profile:     gosrm.ProfileDriving,
	Coordinates: []gosrm.Coordinate{{13.388860, 52.517037}, {13.397634, 52.529407}, {13.428555, 52.523219}, {13.418555, 52.523215}},
    }, gosrm.WithSource(gosrm.SourceFirst), gosrm.WithDestination(gosrm.DestinationLast))
    checkErr(err)

    fmt.Println("\n### Trip Response ###")
    fmt.Printf("%#v\n", tripRes)
    fmt.Println("##########")
}

func checkErr(err error) {
    if err != nil {
	panic(err)
    }
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Annotation

type Annotation struct {
	// Distance is the distance, in metres, between each pair of coordinates.
	Distance []float32 `json:"distance"`

	// Duration is the duration between each pair of coordinates, in seconds.
	Duration []float32 `json:"duration"`

	// DataSources is the index of the datasource for the speed between each pair of coordinates.
	// 0 is the default profile, other values are supplied via --segment-speed-file to osrm-contract.
	DataSources []uint16 `json:"datasources"`

	// Nodes is the OSM node ID for each coordinate along the route, excluding the first/last user-supplied coordinates.
	Nodes []uint64 `json:"nodes"`

	// Weight is the weights between each pair of coordinates. Does not include any turn costs.
	Weight []float32 `json:"Weight"`

	// Speed is the convenience field, calculation of distance / duration rounded to one decimal place.
	Speed []float32 `json:"speed"`

	// Metadata related to other annotations
	Metadata Metadata `json:"metadata"`
}

Annotation of the whole route leg with fine-grained information about each segment or node id.

type Annotations

type Annotations string

Annotations is the type for annotations option.

const (
	// AnnotationsTrue enables annotations.
	AnnotationsTrue Annotations = "true"

	// AnnotationsFalse disables annotations.
	AnnotationsFalse Annotations = "false"

	// AnnotationsNodes is node annotations.
	AnnotationsNodes Annotations = "nodes"

	// AnnotationsSpeed is speed annotations.
	AnnotationsSpeed Annotations = "speed"

	// AnnotationsWeight is weight annotations.
	AnnotationsWeight Annotations = "weight"

	// AnnotationsDistance is distance annotations.
	AnnotationsDistance Annotations = "distance"

	// AnnotationsDuration is duration annotations.
	AnnotationsDuration Annotations = "duration"

	// AnnotationsDataSources is data sources annotations.
	AnnotationsDataSources Annotations = "datasources"

	// AnnotationsDurationDistance is duration and distance annotations.
	AnnotationsDurationDistance Annotations = "duration,distance"
)

type Approaches

type Approaches string

Approaches is the type for approaches option.

const (
	// ApproachesCurb is the curb approaches.
	ApproachesCurb Approaches = "curb"

	// ApproachesUnrestricted is the unrestricted approaches.
	ApproachesUnrestricted Approaches = "unrestricted"
)

type Bearing

type Bearing struct {
	// Value is an integer 0 to 360.
	Value uint16

	// Range is an integer 0 to 180.
	Range uint16
}

Bearing is the {value},{range} bearing type.

type Code

type Code string

Code is the error code returned by OSRM.

const (
	// CodeOK is returned when request could be processed as expected.
	CodeOK Code = "Ok"

	//CodeInvalidUrl is returned when URL string is invalid.
	CodeInvalidUrl Code = "InvalidUrl"

	// CodeInvalidService is returned when service name is invalid.
	CodeInvalidService Code = "InvalidService"

	// CodeInvalidVersion is returned when version is not found.
	CodeInvalidVersion Code = "InvalidVersion"

	// CodeInvalidOptions is returned when options are invalid.
	CodeInvalidOptions Code = "InvalidOptions"

	// CodeInvalidQuery is returned when the query string is synctactically malformed.
	CodeInvalidQuery Code = "InvalidQuery"

	// CodeInvalidValue is returned when the successfully parsed query parameters are invalid.
	CodeInvalidValue Code = "InvalidValue"

	// CodeNoSegment is returned when one of the supplied input coordinates could not snap to street segment.
	CodeNoSegment Code = "NoSegment"

	// CodeTooBig is returned when the request size violates one of the service specific request size restrictions.
	CodeTooBig Code = "TooBig"

	// CodeNoRoute is returned when no route was found.
	CodeNoRoute Code = "NoRoute"

	// CodeNoTable is returned when no route was found.
	CodeNoTable Code = "NoTable"

	// CodeNoMatch is returned when no match was found.
	CodeNoMatch Code = "NoMatch"

	// CodeNoTrips is returned when no trips were found because input coordinates are not connected.
	CodeNoTrips Code = "NoTrips"

	// CodeNotImplemented is returned when this request is not supported.
	CodeNotImplemented Code = "NotImplemented"
)

type ContinueStraight

type ContinueStraight string

ContinueStraight is the type for continue straight option.

const (
	// ContinueStraightDefault is the default continue straight option value.
	ContinueStraightDefault ContinueStraight = "default"

	// ContinueStraightTrue enables continue straight.
	ContinueStraightTrue ContinueStraight = "true"

	// ContinueStraightFalse disables continue straight.
	ContinueStraightFalse ContinueStraight = "false"
)

type Coordinate

type Coordinate [2]float64

Coordinate is a {Lng, Lat} point.

type Destination

type Destination string

Destination is the type for destination option.

const (
	// DestinationAny is the any destination option.
	DestinationAny Destination = "any"

	// DestinationLast is the last destination option.
	DestinationLast Destination = "last"
)

type FallbackCoordinate

type FallbackCoordinate string

FallbackCoordinate is the type for fallback coordinate option.

const (
	// FallbackCoordinateInput when using a fallback_speed, use the user-supplied coordinate (input).
	FallbackCoordinateInput FallbackCoordinate = "input"

	// FallbackCoordinateSnapped when using a fallback_speed, use the snapped location (snapped) for calculating distances.
	FallbackCoordinateSnapped FallbackCoordinate = "snapped"
)

type Gaps

type Gaps string

Gaps is the type for gaps option.

const (
	// GapsSplit is the default gaps option value.
	GapsSplit Gaps = "split"

	// GapsIgnore is the ignore gaps option.
	GapsIgnore Gaps = "ignore"
)

type Geometry

type Geometry string

Geometry is the geometry format.

const (
	// GeometryPolyline is the geometry polyline type.
	GeometryPolyline Geometry = "polyline"

	// GeometryPolyline6 is the geometry polyline6 type.
	GeometryPolyline6 Geometry = "polyline6"

	// GeometryGeoJSON is the geometry geojson type.
	GeometryGeoJSON Geometry = "geojson"
)

type GeometryType

type GeometryType interface {
	string | LineString
}

GeometryType is the type used to represent multiple geometry formats. polyline5, polyline6, geojson.

type HTTPClient added in v0.1.1

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient is the interface that can be used to do HTTP calls.

func NewHTTPClient added in v0.1.1

func NewHTTPClient(cfg HTTPClientConfig) HTTPClient

NewHTTPClient returns a new HTTP client.

type HTTPClientConfig added in v0.1.1

type HTTPClientConfig struct {
	// MaxConcurrency is the max number of concurrent requests.
	// If it's 0 then there is no limit.
	//
	// Defaults to 0.
	MaxConcurrency uint

	// HTTPClient is the client which will be used to do HTTP calls.
	//
	// Defaults to http.DefaultClient
	HTTPClient *http.Client
}

HTTPClientConfig is the config used to customize http client.

type Intersection

type Intersection struct {
	// Location is a [longitude, latitude] pair describing the location of the turn.
	Location Coordinate `json:"location"`

	// Bearings is a list of bearing values (e.g. [0,90,180,270]) that are available at the intersection.
	// The bearings describe all available roads at the intersection.
	Bearings []uint16 `json:"bearings"`

	// Classes is an array of strings signifying the classes (as specified in the profile) of the road exiting the intersection.
	Classes []string `json:"classes"`

	// Entry is a list of entry flags, corresponding in a 1:1 relationship to the bearings.
	// A value of true indicates that the respective road could be entered on a valid route.
	// false indicates that the turn onto the respective road would violate a restriction.
	Entry []bool `json:"entry"`

	// In is the index 	into bearings/entry array. Used to calculate the bearing just before the turn.
	In uint16 `json:"in"`

	// Out is the index into the bearings/entry array. Used to extract the bearing just after the turn.
	Out uint16 `json:"out"`

	// Lanes is an array of Lane objects that denote the available turn lanes at the intersection.
	Lanes []Lane `json:"lanes"`
}

Intersection gives a full representation of any cross-way the path passes bay. For every step, the very first intersection (intersections[0]) corresponds to the location of the StepManeuver. Further intersections are listed for every cross-way until the next turn instruction.

type Lane

type Lane struct {
	// Indications are the indications (e.g. marking on the road) specifying the turn lane.
	Indications []string `json:"indications"`

	// Valid is a boolean flag indicating whether the lane is a valid choice in the current maneuver.
	Valid bool `json:"valid"`
}

Lane represents a turn lane at the corresponding turn location.

type LineString

type LineString struct {
	// Type of the line string.
	Type string `json:"type"`

	// Coordinates of the line string.
	Coordinates []Coordinate `json:"coordinates"`
}

LineString is a GeoJSON line string.

type MatchResponse

type MatchResponse[T GeometryType] struct {
	Response

	// Tracepoints is an array of waypoint objects representing all points of the trace in order.
	// If the trace point was ommited by map matching because it is an outlier, the entry will be null.
	Tracepoints []Tracepoint `json:"tracepoints"`

	// Matchings is an array of route objects that assemble the trace.
	Matchings []Matching[T] `json:"matchings"`
}

MatchResponse is the response of OSRM's match service.

func Match

func Match[T GeometryType](ctx context.Context, osrm OSRMClient, req Request, opts ...Option) (*MatchResponse[T], error)

Match matches/snaps given GPS points to the road network in the most plausible way.

type Matching

type Matching[T GeometryType] struct {
	RouteType[T]

	// Confidence of the matching. float value between 0 and 1. 1 is very confident that the matching is correct.
	Confidence float32 `json:"confidence"`
}

Matching is a route object that assembles the trace.

type Metadata

type Metadata struct {
	// DataSourcesNames is the names of the data sources used for the speed between each pair of coordinates.
	DataSourcesNames []string `json:"datasource_names"`
}

Metadata related to other annotations.

type NearestResponse

type NearestResponse struct {
	Response

	// Waypoints is an array of waypoint objects sorted by distance to the input coordinate.
	Waypoints []NearestWaypoint `json:"waypoints"`
}

NearestResponse is the response of OSRM's nearest service.

func Nearest

func Nearest(ctx context.Context, osrm OSRMClient, req Request, opts ...Option) (*NearestResponse, error)

Nearest snaps a coordinate to the street network and returns the nearest n matches.

type NearestWaypoint

type NearestWaypoint struct {
	Waypoint

	// Nodes is an array of OpenStreetMap node ids.
	Nodes []uint64 `json:"nodes"`
}

NearestWaypoint is the object used to describe nearest waypoint on a route.

type OSRMClient

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

OSRMClient is the base type with helper methods to call OSRM APIs. It only holds the base OSRM URL.

func New

func New(baseURL string) (OSRMClient, error)

New returns a new OSRM client.

func (*OSRMClient) SetHTTPClient added in v0.1.1

func (osrm *OSRMClient) SetHTTPClient(client HTTPClient)

SetHTTPClient sets the HTTP client that will be used to call OSRM.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option is the interface for adding options to requests.

func WithAlternatives

func WithAlternatives(alternatives bool) Option

WithAlternatives makes OSRM to search for alternative routes and return as well. Can be used in route service.

func WithAnnotations

func WithAnnotations(annotations Annotations) Option

WithAnnotations makes OSRM to return additional metadata for each coordinate along the route geometry. Can be used in route, match and trip services.

func WithApproaches

func WithApproaches(approaches []Approaches) Option

WithApproaches keeps waypoints on curbside. It's a general option and can be used in all services.

func WithBearings

func WithBearings(bearings []Bearing) Option

WithBearings limits the search to segments with given bearing in degrees towards true north in a clockwise direction. It's a general option and can be used in all services.

func WithContinueStraight

func WithContinueStraight(cs ContinueStraight) Option

WithContinueStraight forces the route to keep going straight at waypoints constraining uturns there even if it would be faster. Default value depends on the profile. Can be used in route service.

func WithCustomOption

func WithCustomOption(option, value string) Option

WithCustomOption sets a custom option. Can be used if an option is not provided by the package.

func WithDestination

func WithDestination(dest Destination) Option

WithDestination is used when the returned route ends at any or last coordinate. Can be used in trip service.

func WithDestinations

func WithDestinations(destinations []uint16) Option

WithDestinations uses location with given index as destination. If the slice is empty uses all. Can be used in table service.

func WithExclude

func WithExclude(classes []string) Option

WithExclude is an additive list of classes to avoid, the order does not matter. A class name determined by the profile or none. It's a general option and can be used in all services.

func WithFallbackCoordinate

func WithFallbackCoordinate(fc FallbackCoordinate) Option

WithFallbackCoordinate when using a fallback_speed, use the user-supplied coordinate (input), or the snapped location (snapped) for calculating distances. Can be used in table service.

func WithFallbackSpeed

func WithFallbackSpeed(speed float64) Option

WithFallbackSpeed is used if no route found between a source/destination pair, calculate the as-the-crow-flies distance, then use this speed to estimate duration. should be greater than 0. Can be used in table service.

func WithGaps

func WithGaps(gaps Gaps) Option

WithGaps allows the input track splitting based on huge timestamp gaps between points. Can be used in match service.

func WithGenerateHints

func WithGenerateHints(generate bool) Option

WithGenerateHints adds a hint to the response which can be used in subsequent requests. It's a general option and can be used in all services.

func WithGeometries

func WithGeometries(geometry Geometry) Option

WithGeometries sets the returned route geometry format (influences overview and per step). Can be used in route, match and trip services.

func WithHints

func WithHints(hints []string) Option

WithHints is hint from previous request to derive position in street network. Hint is a base64 string. It's a general option and can be used in all services.

func WithNumber

func WithNumber(number uint8) Option

WithNumber sets number of nearest segments that should be returned. It should be >= 1. Can only used with nearest service.

func WithOverview

func WithOverview(overview Overview) Option

WithOverview adds overview geometry either full, simplified according to highest zoom level it could be display on, or not at all. Can be used in route, match and trip services.

func WithRadiuses

func WithRadiuses(radiuses []float32) Option

WithRadiuses limits the search to given radius in meters. It's a general option and can be used in all services.

func WithRoundTrip

func WithRoundTrip(isRound bool) Option

WithRoundTrip is used when the returned route is a roundtrip (route returns to first location). Can be used in trip service.

func WithScaleFactor

func WithScaleFactor(sf float64) Option

WithScaleFactor should be uses in conjunction with annotations=durations. Scales the table duration values by this number. Can be used in table service.

func WithSkipWaypoints

func WithSkipWaypoints(skip bool) Option

WithSkipWaypoints removes waypoints from the response. Waypoints are still calculated, but not serialized. Could be useful in case you are interested in some other part of the response and do not want to transfer waste data. It's a general option and can be used in all services.

func WithSnapping

func WithSnapping(snapping Snapping) Option

WithSnapping default snapping avoids is_startpoint (see profile) edges, any will snap to any edge in the graph. It's a general option and can be used in all services.

func WithSource

func WithSource(source Source) Option

WithSource is used when the returned route starts at any or first coordinate. Can be used in trip service.

func WithSources

func WithSources(sources []uint16) Option

WithSources uses location with given index as source. If the slice is empty uses all. Can be used in table service.

func WithSteps

func WithSteps(steps bool) Option

WithSteps makes OSRM to return route steps for each route leg. Can be used in route, match and trip services.

func WithTidy

func WithTidy(tidy bool) Option

WithTidy allows the input track modification to obtain better matching quality for noisy tracks. Can be used in match service.

func WithTimestamps

func WithTimestamps(timestamps []int64) Option

WithTimestamps adds timestamps of the input locations in UNIX seconds. Timestamps need to be monotonically increasing. Can be used in match service.

func WithWaypoints

func WithWaypoints(waypoints []uint16) Option

WithWaypoints treats input coordinates indicated by given indices as waypoints in returned Match object. Default is to treat all input coordinates as waypoints. Can be used in route and match services.

type Overview

type Overview string

Overview is the type for overview option.

const (
	// OverviewSimplified is the simplified overview.
	OverviewSimplified Overview = "simplified"

	// OverviewFull is the full overview.
	OverviewFull Overview = "full"

	// OverviewFalse disables the overview.
	OverviewFalse Overview = "false"
)

type Profile

type Profile string

Profile is the mode of transportation, is determined statically by the Lua profile that is used to prepare the data using osrm-extract. Typically car, bike or foot if using one of the supplied profiles.

const (
	// ProfileDriving is the driving transportation mode.
	ProfileDriving Profile = "driving"

	// ProfileCar is the car transportation mode.
	ProfileCar Profile = "car"

	// ProfileBike is the bike transportation mode.
	ProfileBike Profile = "bike"

	// ProfileFoot is the foot transportation mode.
	ProfileFoot Profile = "foot"
)

type Request

type Request struct {
	// Profile is the profile of the request.
	Profile Profile

	// Coordinates is the coordinate of the request.
	Coordinates []Coordinate
}

Request is the OSRM's request structure. It can be used with all services except tile service. Note that for nearest request you have to pass only a coordinate.

type Response

type Response struct {
	// Code is the error code returned by OSRM.
	Code Code `json:"code"`

	// Message is a optional human-readable error message.
	Message string `json:"message"`

	DataVersion time.Time `json:"data_version"`
}

Response is the common fields which are used in all of the OSRM services responses.

func (Response) IsOk added in v0.1.1

func (res Response) IsOk() bool

IsOk returns true if request could be processed as expected by OSRM.

type RouteLeg

type RouteLeg[T GeometryType] struct {
	// Distance is the distance traveled by this route leg, in meters.
	Distance float32 `json:"distance"`

	// Duration is the estimated travel time, in seconds.
	Duration float32 `json:"duration"`

	// Summary of the route taken as string. Depends on the steps parameter.
	Summary string `json:"summary"`

	// Weight is the calculated weight of the route leg.
	Weight float32 `json:"weight"`

	// Annotation is additional details about each coordinate along the route geometry.
	Annotation Annotation `json:"annotation"`

	// Steps are route steps of the route leg.
	// if geometries is geojson	use LineString otherwise use string.
	Steps []RouteStep[T] `json:"steps"`
}

RouteLeg represents a route between two waypoints.

type RouteResponse

type RouteResponse[T GeometryType] struct {
	Response

	Routes    []RouteType[T] `json:"routes"`
	Waypoints []Waypoint     `json:"waypoints"`
}

RouteResponse is the response of OSRM's route service.

func Route

func Route[T GeometryType](ctx context.Context, osrm OSRMClient, req Request, opts ...Option) (*RouteResponse[T], error)

Route finds the fastest route between coordinates in the supplied order.

type RouteStep

type RouteStep[T GeometryType] struct {
	// Distance is the distance of travel from the maneuver to the subsequent step, in meters.
	Distance float32 `json:"distance"`

	// Duration is the estimated travel time, in float number of seconds.
	Duration float32 `json:"duration"`

	// Weight is the calculated weight of the step.
	Weight float32 `json:"weight"`

	// Exits is the exit numbers or names of the way. Will be undefined if there are no exit numbers or names.
	Exits uint16 `json:"exits"`

	// Name of the way along which travel proceeds.
	Name string `json:"name"`

	// Ref a reference number or code for the way. Optionally included, if ref data is available for the given way.
	Ref string `json:"ref"`

	// Pronunciation is the pronunciation hint of the way name. Will be undefined if there is no pronunciation hit.
	Pronunciation string `json:"pronunciation"`

	// RotaryName is the name for the rotary. Optionally included, if the step is a rotary and a rotary name is available.
	RotaryName string `json:"rotary_name"`

	// RotaryPronunciation is the pronunciation hint of the rotary name.
	// Optionally included, if the step is a rotary and a rotary pronunciation is available.
	RotaryPronunciation string `json:"rotary_pronunciation"`

	// DrivingSide is the legal driving side at the location for this step. Either left or right.
	DrivingSide string `json:"driving_side"`

	// Destinations of the way. Will be undefined if there are no destinations.
	Destinations []Waypoint `json:"destinations"`

	// Mode is a string signifying the mode of transportation.
	Mode string `json:"mode"`

	// Intersections is a list of Intersection objects that are passed along the segment, the very first belonging to the StepManeuver.
	Intersections []Intersection `json:"intersections"`

	// Maneuver represents the maneuver.
	Maneuver StepManeuver `json:"maneuver"`

	// Geometry is the unsimplified geometry of the route segment, depending on the geometries parameter.
	// if geometries is geojson	use LineString otherwise use string.
	Geometry T `json:"geometry"`
}

RouteStep consists of a maneuver such as a turn or merge, followed by a distance of travel along a single way to the subsequent step.

type RouteType

type RouteType[T GeometryType] struct {
	// Distance is the distance traveled by the route, in meters.
	Distance float32 `json:"distance"`

	// Duration	is the estimated travel time, in seconds.
	Duration float32 `json:"duration"`

	// Weight is the calculated weight of the route.
	Weight float32 `json:"weight"`

	// WeightName is the name of the weight profile used during the extraction phase.
	WeightName string `json:"weight_name"`

	// Legs are the legs between the given waypoints.
	// if geometries is geojson	use LineString otherwise use string.
	Legs []RouteLeg[T] `json:"legs"`

	// Geometry is the whole geometry of the route value depending on overview parameter, format depending on the geometries parameter.
	// if geometries is geojson	use LineString otherwise use string.
	Geometry T `json:"geometry"`
}

RouteType represents a route through (potentially multiple) waypoints.

type Snapping

type Snapping string

Snapping is the type for snapping option.

const (
	// SnappingDefault is the default snapping.
	SnappingDefault Snapping = "default"

	// SnappingAny is the any snapping.
	SnappingAny Snapping = "any"
)

type Source

type Source string

Source is the type for source option.

const (
	// SourceAny is the any source option.
	SourceAny Source = "any"

	// SourceFirst is the first source option.
	SourceFirst Source = "first"
)

type StepManeuver

type StepManeuver struct {
	// Location is a [longitude, latitude] pair describing the location of the turn.
	Location Coordinate `json:"location"`

	// BearingBefore is the clockwise angle from true north to the direction of travel immediately before the maneuver.
	BearingBefore float32 `json:"bearing_before"`

	// BearingAfter is the clockwise angle from true north to the direction of travel immediately before the maneuver.
	BearingAfter float32 `json:"bearing_after"`

	// Type is a string indicating the type of maneuver.
	Type string `json:"type"`

	// Modifier is an optional string indicating the direction change of the maneuver.
	Modifier string `json:"modifier"`

	// Exit is an optional integer indicating number of the exit to take.
	Exit uint16 `json:"exit"`
}

StepManeuver holds information about maneuver in a step.

type TableResponse

type TableResponse struct {
	Response

	// Durations is an array of arrays that stores the matrix in row-major order.
	// durations[i][j] gives the travel time from the i-th waypoint to the j-th waypoint, in seconds.
	Durations [][]float32 `json:"durations"`

	// Distances is an array of arrays that stores the matrix in row-major order.
	// distances[i][j] gives the travel distance from the i-th source to the j-th destination, in meters.
	Distances [][]float32 `json:"distances"`

	// Destinations is an array of Waypoint objects describing all destinations in order.
	Destinations []Waypoint `json:"destinations"`

	// Sources is an array of Waypoint objects describing all sources in order.
	Sources []Waypoint `json:"sources"`

	// FallbackSpeedCells is an optional array of arrays containing i,j pairs indicating
	// which cells contain estimated values based on fallback_speed.
	// Will be absent if fallback_speed is not used.
	FallbackSpeedCells [][]uint16 `json:"fallback_speed_cells"`
}

TableResponse is the response of OSRM's table service.

func Table

func Table(ctx context.Context, osrm OSRMClient, req Request, opts ...Option) (*TableResponse, error)

Table computes the duration of the fastest route between all pairs of supplied coordinates.

type Tracepoint

type Tracepoint struct {
	Waypoint

	// WaypointIndex is the index of the waypoint inside the matched route.
	WaypointIndex uint16 `json:"waypoint_index"`

	// MatchingIndex is the index to the Route object in matchings the sub-trace was matched to.
	MatchingIndex uint16 `json:"matchings_index"`

	// AlternativesCount is the number of probable alternative matchings for this tracepoint.
	// A value of zero indicates that this point was matched unambiguously.
	// Split the trace at these points for incremental map matching.
	AlternativesCount uint16 `json:"alternatives_count"`
}

Tracepoint is a waypoint object representing a point of the trace.

type TripResponse

type TripResponse[T GeometryType] struct {
	Response

	// Waypoints is an array of waypoint objects representing all waypoints in input order.
	Waypoints []TripWaypoint `json:"waypoints"`

	// Trips is an array of Route objects that assemble the trace.
	Trips []RouteType[T] `json:"trips"`
}

TripResponse is the response of OSRM's trip service.

func Trip

func Trip[T GeometryType](ctx context.Context, osrm OSRMClient, req Request, opts ...Option) (*TripResponse[T], error)

Trip service solves the Traveling Salesman Problem using a greedy heuristic (farthest-insertion algorithm) for 10 or more waypoints and uses brute force for less than 10 waypoints. The returned path does not have to be the fastest one. As TSP is NP-hard it only returns an approximation. Note that all input coordinates have to be connected for the trip service to work.

type TripWaypoint

type TripWaypoint struct {
	Waypoint

	// TripsIndex is the index to trips of the sub-trip the point was matched to.
	TripsIndex uint16 `json:"trips_index"`

	// WaypointIndex is the index of the point in the trip.
	WaypointIndex uint16 `json:"waypoint_index"`
}

TripWaypoint is the object used to describe trip waypoint on a route.

type Waypoint

type Waypoint struct {
	// Name of the street the coordinate snapped to
	Name string `json:"name"`

	// Hint is an unique internal identifier of the segment (ephemeral, not constant over data updates)
	// This can be used on subsequent request to significantly speed up the query and to connect multiple services.
	// E.g. you can use the hint value obtained by the nearest query as hint values for route inputs.
	Hint string `json:"hint"`

	// Distance of the snapped point from the original, in meters.
	Distance float32 `json:"distance"`

	// Location is an array that contains the [longitude, latitude] pair of the snapped coordinate
	Location Coordinate `json:"location"`
}

Waypoint is the object used to describe waypoint on a route.

Jump to

Keyboard shortcuts

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