osrm

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2022 License: BSD-3-Clause Imports: 14 Imported by: 0

README

Go client library for OSRM

GoDoc Build Status Go Report Card codecov

Description

Currently supported OSRM APIs are:

Not implemeted yet:

Usage

Sample usage:

package main

import (
	"context"
	"log"
	"time"

	osrm "github.com/gojuno/go.osrm"
	geo "github.com/paulmach/go.geo"
)

func main() {
	client := osrm.NewFromURL("https://router.project-osrm.org")

	ctx, cancelFn := context.WithTimeout(context.Background(), time.Second)
	defer cancelFn()

	resp, err := client.Route(ctx, osrm.RouteRequest{
		Profile: "car",
		Coordinates: osrm.NewGeometryFromPointSet(geo.PointSet{
			{-73.980020, 40.751739},
			{-73.962662, 40.794156},
		}),
		Steps:       osrm.StepsTrue,
		Annotations: osrm.AnnotationsTrue,
		Overview:    osrm.OverviewFalse,
		Geometries:  osrm.GeometriesPolyline6,
	})
	if err != nil {
		log.Fatalf("route failed: %v", err)
	}

	log.Printf("routes are: %+v", resp.Routes)
}

Documentation

Overview

Package osrm provides a client library for OSRM API. Please see https://github.com/Project-OSRM/osrm-backend/blob/master/docs/http.md for API overview.

Index

Examples

Constants

View Source
const (
	ErrorCodeInvalidURL     = "InvalidUrl"
	ErrorCodeInvalidService = "InvalidService"
	ErrorCodeInvalidVersion = "InvalidVersion"
	ErrorCodeInvalidOptions = "InvalidOptions"
	ErrorCodeInvalidQuery   = "InvalidQuery"
	ErrorCodeInvalidValue   = "InvalidValue"
	ErrorCodeNoSegment      = "NoSegment"
	ErrorCodeTooBig         = "TooBig"
	ErrorCodeNoRoute        = "NoRoute"
	ErrorCodeNoTable        = "NoTable"
	ErrorCodeNoMatch        = "NoMatch"
)

Error codes that could be returned from OSRM

Variables

View Source
var (
	ErrEmptyProfileName = errors.New("osrm5: the request should contain a profile name")
	ErrNoCoordinates    = errors.New("osrm5: the request should contain coordinates")
	ErrEmptyServiceName = errors.New("osrm5: the request should contain a service name")
)

Invalid request errors

Functions

This section is empty.

Types

type Annotation

type Annotation struct {
	Duration []float32 `json:"duration,omitempty"`
	Distance []float32 `json:"distance,omitempty"`
	Nodes    []uint64  `json:"nodes,omitempty"`
}

Annotation contains additional metadata for each coordinate along the route geometry

type Annotations

type Annotations string

Annotations represents a annotations param for osrm5 request

const (
	AnnotationsTrue            Annotations = "true"
	AnnotationsFalse           Annotations = "false"
	AnnotationsNodes           Annotations = "nodes"
	AnnotationsDistance        Annotations = "distance"
	AnnotationsDuration        Annotations = "duration"
	AnnotationDurationDistance Annotations = "duration,distance"
	AnnotationsDatasources     Annotations = "datasources"
	AnnotationsWeight          Annotations = "weight"
	AnnotationsSpeed           Annotations = "speed"
)

Supported annotations param values

func (Annotations) String

func (a Annotations) String() string

String returns Annotations as a string

type Bearing

type Bearing struct {
	Value, Range uint16
}

Bearing limits the search to segments with given bearing in degrees towards true north in clockwise direction.

func (Bearing) String

func (b Bearing) String() string

type Config

type Config struct {
	// ServerURL is OSRM server URL to be used for queries.
	// Local http://127.0.0.1:5000 URL will be used as default if not set.
	ServerURL string
	// Client is custom pre-configured http client to be used for queries.
	// New http.Client instance with default settings and one second timeout will be used if not set.
	Client HTTPClient
}

Config represents OSRM client configuration options

type ContinueStraight

type ContinueStraight string

ContinueStraight represents continue_straight OSRM routing parameter

const (
	ContinueStraightDefault ContinueStraight = "default"
	ContinueStraightTrue    ContinueStraight = "true"
	ContinueStraightFalse   ContinueStraight = "false"
)

ContinueStraight values

func (ContinueStraight) String

func (c ContinueStraight) String() string

String returns ContinueStraight as string

type Gaps

type Gaps string

Gaps represents a gaps param for osrm5 match request

const (
	GapsSplit  Gaps = "split"
	GapsIgnore Gaps = "ignore"
)

Supported gaps param values

func (Gaps) String

func (g Gaps) String() string

String returns Gaps as a string

type Geometries

type Geometries string

Geometries represents a geometries param for osrm5

const (
	GeometriesPolyline6 Geometries = "polyline6"
	GeometriesGeojson   Geometries = "geojson"
)

Supported geometries param values

func (Geometries) String

func (g Geometries) String() string

String returns Geometries as a string

type Geometry

type Geometry struct {
	geo.Path
}

Geometry represents a points set

func NewGeometryFromPath

func NewGeometryFromPath(path geo.Path) Geometry

NewGeometryFromPath creates a geometry from a path.

func NewGeometryFromPointSet

func NewGeometryFromPointSet(ps geo.PointSet) Geometry

NewGeometryFromPointSet creates a geometry from points set.

func (Geometry) MarshalJSON

func (g Geometry) MarshalJSON() ([]byte, error)

MarshalJSON generates a polyline in Google polyline6 format

func (*Geometry) Polyline

func (g *Geometry) Polyline(factor ...int) string

Polyline generates a polyline in Google format

func (*Geometry) UnmarshalJSON

func (g *Geometry) UnmarshalJSON(b []byte) error

UnmarshalJSON parses a geo path from points set or a polyline

type HTTPClient

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

HTTPClient defines minimal interface necessary for making HTTP requests. Standard library http.Client{} implements this interface. A non-2xx status code doesn't cause an error.

type Intersection

type Intersection struct {
	Location geo.Point `json:"location"`
	Bearings []uint16  `json:"bearings"`
	Entry    []bool    `json:"entry"`
	In       *uint32   `json:"in,omitempty"`
	Out      *uint32   `json:"out,omitempty"`
	Lanes    []Lane    `json:"lanes,omitempty"`
}

type Lane

type Lane struct {
	Indications []string `json:"indications"`
	Valid       bool     `json:"valid"`
}

type MatchRequest

type MatchRequest struct {
	Profile     string
	Coordinates Geometry
	Bearings    []Bearing
	Steps       Steps
	Annotations Annotations
	Tidy        Tidy
	Timestamps  []int64
	Radiuses    []float64
	Hints       []string
	Overview    Overview
	Gaps        Gaps
	Geometries  Geometries
}

MatchRequest represents a request to the match method

type MatchResponse

type MatchResponse struct {
	ResponseStatus
	Matchings   []Matching    `json:"matchings"`
	Tracepoints []*Tracepoint `json:"tracepoints"`
}

MatchResponse represents a response from the match method

type Matching

type Matching struct {
	Route
	Confidence float64  `json:"confidence"`
	Geometry   Geometry `json:"geometry"`
}

Matching represents an array of Route objects that assemble the trace

type NearestRequest

type NearestRequest struct {
	Profile     string
	Coordinates Geometry
	Bearings    []Bearing
	Number      int
}

NearestRequest represents a request to the nearest method

type NearestResponse

type NearestResponse struct {
	ResponseStatus
	Waypoints []NearestWaypoint `json:"waypoints"`
}

NearestResponse represents a response from the nearest method

type NearestWaypoint

type NearestWaypoint struct {
	Location geo.Point `json:"location"`
	Distance float64   `json:"distance"`
	Name     string    `json:"name"`
	Hint     string    `json:"hint"`
	Nodes    []uint64  `json:"nodes"`
}

NearestWaypoint represents a nearest point on a nearest query

type OSRM

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

OSRM implements the common OSRM API v5. See https://github.com/Project-OSRM/osrm-backend/blob/master/docs/http.md for details. TODO: implement (trip, tile) methods

func New

func New() *OSRM

New creates a client with default server url and default timeout

func NewFromURL

func NewFromURL(serverURL string) *OSRM

NewFromURL creates a client with custom server url and default timeout

func NewFromURLWithTimeout

func NewFromURLWithTimeout(serverURL string, timeout time.Duration) *OSRM

NewFromURLWithTimeout creates a client with custom timeout connection

func NewWithConfig

func NewWithConfig(cfg Config) *OSRM

NewWithConfig creates a client with given config

func (OSRM) Match

func (o OSRM) Match(ctx context.Context, r MatchRequest) (*MatchResponse, error)

Match matches given GPS points to the road network in the most plausible way. See https://github.com/Project-OSRM/osrm-backend/blob/master/docs/http.md#match-service for details.

func (OSRM) Nearest

func (o OSRM) Nearest(ctx context.Context, r NearestRequest) (*NearestResponse, error)

Nearest matches given GPS point to the nearest road network. See https://github.com/Project-OSRM/osrm-backend/blob/master/docs/http.md#nearest-service for details.

func (OSRM) Route

func (o OSRM) Route(ctx context.Context, r RouteRequest) (*RouteResponse, error)

Route searches the shortest path between given coordinates. See https://github.com/Project-OSRM/osrm-backend/blob/master/docs/http.md#route-service for details.

Example
package main

import (
	"context"
	"fmt"
	"log"

	osrm "github.com/gojuno/go.osrm"
	geo "github.com/paulmach/go.geo"
)

func main() {
	client := osrm.NewFromURL("https://router.project-osrm.org")

	resp, err := client.Route(context.Background(), osrm.RouteRequest{
		Profile: "car",
		Coordinates: osrm.NewGeometryFromPointSet(geo.PointSet{
			{-73.87946, 40.75833},
			{-73.87925, 40.75837},
			{-73.87918, 40.75837},
			{-73.87911, 40.75838},
		}),
		Steps:       osrm.StepsTrue,
		Annotations: osrm.AnnotationsTrue,
		Overview:    osrm.OverviewFalse,
		Geometries:  osrm.GeometriesPolyline6,
	})
	if err != nil {
		log.Fatalf("route failed: %v", err)
	}

	fmt.Println(len(resp.Routes))

}
Output:

1

func (OSRM) Table

func (o OSRM) Table(ctx context.Context, r TableRequest) (*TableResponse, error)

Table computes duration tables for the given locations. See https://github.com/Project-OSRM/osrm-backend/blob/master/docs/http.md#table-service for details.

type Overview

type Overview string

Overview represents level of overview of geometry in a response

const (
	OverviewSimplified Overview = "simplified"
	OverviewFull       Overview = "full"
	OverviewFalse      Overview = "false"
)

Available overview values

func (Overview) String

func (o Overview) String() string

String returns Overview as a string

type ResponseStatus

type ResponseStatus struct {
	Code        string `json:"code"`
	Message     string `json:"message"`
	DataVersion string `json:"data_version"`
}

ResponseStatus represent OSRM API response

func (ResponseStatus) ErrCode

func (r ResponseStatus) ErrCode() string

ErrCode returns error code from OSRM response

func (ResponseStatus) Error

func (r ResponseStatus) Error() string

type Route

type Route struct {
	Distance   float32    `json:"distance"`
	Duration   float32    `json:"duration"`
	WeightName string     `json:"weight_name"`
	Wieght     float32    `json:"weight"`
	Geometry   Geometry   `json:"geometry"`
	Legs       []RouteLeg `json:"legs"`
}

Route represents a route through (potentially multiple) points.

type RouteLeg

type RouteLeg struct {
	Annotation Annotation  `json:"annotation"`
	Distance   float32     `json:"distance"`
	Duration   float32     `json:"duration"`
	Summary    string      `json:"summary"`
	Weight     float32     `json:"weight"`
	Steps      []RouteStep `json:"steps"`
}

RouteLeg represents a route between two waypoints.

type RouteRequest

type RouteRequest struct {
	Profile          string
	Coordinates      Geometry
	Bearings         []Bearing
	Steps            Steps
	Annotations      Annotations
	Overview         Overview
	Geometries       Geometries
	ContinueStraight ContinueStraight
	Waypoints        []int
}

RouteRequest represents a request to the route method

type RouteResponse

type RouteResponse struct {
	ResponseStatus
	Routes    []Route    `json:"routes"`
	Waypoints []Waypoint `json:"waypoints"`
}

RouteResponse represents a response from the route method

type RouteStep

type RouteStep struct {
	Distance      float32        `json:"distance"`
	Duration      float32        `json:"duration"`
	Geometry      Geometry       `json:"geometry"`
	Name          string         `json:"name"`
	Mode          string         `json:"mode"`
	DrivingSide   string         `json:"driving_side"`
	Weight        float32        `json:"weight"`
	Maneuver      StepManeuver   `json:"maneuver"`
	Intersections []Intersection `json:"intersections,omitempty"`
}

RouteStep represents a route geometry

type StepManeuver

type StepManeuver struct {
	Location      geo.Point `json:"location"`
	BearingBefore float32   `json:"bearing_before"`
	BearingAfter  float32   `json:"bearing_after"`
	Type          string    `json:"type"`
	Modifier      string    `json:"modifier,omitempty"`
	Exit          *uint32   `json:"exit,omitempty"`
}

StepManeuver contains information about maneuver in step

type Steps

type Steps string

Steps represents a steps param for osrm5 request

const (
	StepsTrue  Steps = "true"
	StepsFalse Steps = "false"
)

Supported steps param values

func (Steps) String

func (s Steps) String() string

String returns Steps as a string

type TableRequest

type TableRequest struct {
	Profile               string
	Coordinates           Geometry
	Sources, Destinations []int
	Annotations           Annotations
}

TableRequest represents a request to the table method

type TableResponse

type TableResponse struct {
	ResponseStatus
	Durations [][]float32 `json:"durations"`
	Distances [][]float32 `json:"distances"`
}

TableResponse resresents a response from the table method

type Tidy

type Tidy string

Tidy represents a tidy param for osrm5 match request

const (
	TidyTrue  Tidy = "true"
	TidyFalse Tidy = "false"
)

Supported tidy param values

func (Tidy) String

func (t Tidy) String() string

String returns Tidy as a string

type Tracepoint

type Tracepoint struct {
	Index             int       `json:"waypoint_index"`
	Location          geo.Point `json:"location"`
	MatchingIndex     int       `json:"matchings_index"`
	AlternativesCount int       `json:"alternatives_count"`
	Hint              string    `json:"hint"`
}

Tracepoint represents a matched point on a route

type Waypoint

type Waypoint struct {
	Name     string    `json:"name"`
	Location geo.Point `json:"location"`
	Distance float32   `json:"distance"`
	Hint     string    `json:"hint"`
}

Jump to

Keyboard shortcuts

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