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

gosrm

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2020 License: MIT Imports: 12 Imported by: 0

README

GOSRM - GO Client for OSRM

Build Status godoc License Go Report Card

Advanced OSRM client for golang.

Features

  • Route Client

Installation

go get github.com/karmadon/gosrm

Quick Start

Route Service
package main

import (
	"fmt"
	"net/url"
	"github.com/karmadon/gosrm"
	"github.com/paulmach/go.geo"
)

func main() {
    options := &gosrm.Options{
        Url:            url.URL{Host: "https://router.project-osrm.org/"},
        Service:        consts.ServiceRoute,
        Version:        consts.VersionFirst,
        Profile:        consts.ProfileDriving,
        RequestTimeout: 5,
    }

    client := gosrm.NewClient(options)

    routeRequest := &models.RouteRequest{
        Coordinates: geo.PointSet{{36.232051849365234, 49.98765584451778}, {36.22089385986328, 50.03718650830641}},
    }

    response, err := client.Route(routeRequest)
    if err != nil {
        panic(err.Error())
    }

    fmt.Printf("%#v", response)
}
Table Service
package main

import (
	"fmt"
	"net/url"
	"github.com/karmadon/gosrm"
	"github.com/paulmach/go.geo"
)

func main() {
	options := &gosrm.Options{
		Url:            url.URL{Host: "https://router.project-osrm.org/"},
		Service:        consts.ServiceTable,
		Version:        consts.VersionFirst,
		Profile:        consts.ProfileDriving,
		RequestTimeout: 5,
	}

	client := gosrm.NewClient(options)

	sources := []int{1, 2}
	destinations := []int{2, 1}

	annotation := consts.TableAnnotationDurationDistance
	scaleFactor := 1.2

	tableRequest := &models.TableRequest{
		Coordinates:  geo.PointSet{{36.232051849365234, 49.98765584451778}, {36.22089385986328, 50.03718650830641}},
		Sources:      &sources,
		Destinations: &destinations,
		Annotations:  &annotation,
		ScaleFactor:  &scaleFactor,
	}

	response, err := client.Table(tableRequest)
	if err != nil {
		panic(err.Error())
	}

	fmt.Printf("%#v", response)
}
Full Example

See examples folder

Documentation

Index

Constants

View Source
const (
	ClientMaxIdleConnections  = 1024
	ClientTLSHandshakeTimeout = 1 * time.Second
)
View Source
const (
	// Lib Version
	Version = "0.1.0"

	// Finds the fastest route between coordinates in the supplied order
	ServiceRoute = "route"

	// Snaps a coordinate to the street network and returns the nearest n matches
	ServiceNearest = "nearest"

	// Computes the duration of the fastest route between all pairs of supplied coordinates
	ServiceTable = "table"

	// Map matching matches/snaps given GPS points to the road network in the most plausible way
	ServiceMatch = "match"

	// The trip plugin 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.
	ServiceTrip = "trip"

	// This service generates Mapbox Vector Tiles that can be viewed with a vector-tile capable slippy-map viewer.
	ServiceTile = "tile"

	// Standard profile
	ProfileDriving = "driving"

	// Car profile
	ProfileCar = "car"

	// Foot profile
	ProfileFoot = "foot"

	// First and only (for now) version of OSRM api
	VersionFirst = "v1"
)
View Source
const CodeOK = "Ok"

Variables

View Source
var RespCode = map[string]string{
	"NoRoute":        "No route found",
	"NoTable":        "No route found in table method.",
	"NoMatch":        "No matching found.",
	"NoTrips":        "No trips found because input coordinates are not connected.",
	"NotImplemented": "This request is not supported",
	"InvalidUrl":     "URL string is invalid",
	"Ok":             "All OK",
	"InvalidService": "Service name is invalid.",
	"InvalidVersion": "OSRM Version is not found.",
	"InvalidOptions": "Options are invalid.",
	"InvalidQuery":   "The query string is syntactically malformed.",
	"InvalidValue":   "The successfully parsed query parameters are invalid.",
	"NoSegment":      "One of the supplied input coordinates could not snap to street segment.",
	"TooBig":         "The request size violates one of the service specific request size restrictions",
}

Errors which could be returned from OSRM Server

Functions

This section is empty.

Types

type Annotation

type Annotation struct {
	Metadata    Metadata      `json:"metadata,omitempty"`
	Nodes       []interface{} `json:"nodes,omitempty"`
	Datasources []int         `json:"datasources,omitempty"`
	Speed       []float64     `json:"speed,omitempty"`
	Weight      []float64     `json:"weight,omitempty"`
	Duration    []float64     `json:"duration,omitempty"`
	Distance    []float64     `json:"distance,omitempty"`
}

type Destination

type Destination struct {
	Hint     string    `json:"hint,omitempty"`
	Name     string    `json:"name,omitempty"`
	Location []float64 `json:"location,omitempty"`
}

For Table Request

type FallbackCoordinate added in v0.1.1

type FallbackCoordinate string

Return the requested table or tables in response

const (
	// default
	FallbackCoordinateInput   FallbackCoordinate = "input"
	FallbackCoordinateSnapped FallbackCoordinate = "snapped"
)

func (*FallbackCoordinate) String added in v0.1.1

func (a *FallbackCoordinate) String() string

type GOSRMError added in v0.1.0

type GOSRMError struct {
	Url         *url.URL
	Err         error
	RawResponse *[]byte
}

func NewGOSRMError added in v0.1.0

func NewGOSRMError(url *url.URL, err error, rawResponse *[]byte) *GOSRMError

func (*GOSRMError) Error added in v0.1.0

func (e *GOSRMError) Error() string

type Intersection

type Intersection struct {
	Out      int       `json:"out,omitempty"`
	Entry    []bool    `json:"entry,omitempty"`
	Bearings []int     `json:"bearings,omitempty"`
	Location []float64 `json:"location,omitempty"`
}

type Leg

type Leg struct {
	Annotation Annotation `json:"annotation,omitempty"`
	Steps      []Step     `json:"steps,omitempty"`
	Distance   float64    `json:"distance,omitempty"`
	Duration   float64    `json:"duration,omitempty"`
	Summary    string     `json:"summary,omitempty"`
	Weight     float64    `json:"weight,omitempty"`
}

OSRM Leg

type Maneuver

type Maneuver struct {
	BearingAfter  int       `json:"bearing_after,omitempty"`
	Type          string    `json:"type,omitempty"`
	Modifier      string    `json:"modifier,omitempty"`
	BearingBefore int       `json:"bearing_before,omitempty"`
	Location      []float64 `json:"location,omitempty"`
}

type MatchRequest

type MatchRequest struct {
	// coordinates
	Coordinates geo.PointSet `json:"coordinates"`
}

type Metadata

type Metadata struct {
	DatasourceNames []string `json:"datasource_names,omitempty"`
}

type NearestRequest

type NearestRequest struct {
	// coordinates
	Coordinates geo.Point `json:"coordinates"`

	// Number of nearest segments that should be returned
	Number *int `json:"number"`
}

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

type OSRM

type OSRM interface {
	Route(r *RouteRequest) (*OSRMResponse, error)
	Table(r *TableRequest) (*OSRMResponse, error)
	Match(r *MatchRequest) (*OSRMResponse, error)
	Nearest(r *NearestRequest) (*OSRMResponse, error)
}

type OSRMResponse

type OSRMResponse struct {
	// Response code
	Code string `json:"code,omitempty"`
	// Response message for errors
	Message string `json:"message,omitempty"`
	// Routes array object
	Routes []Route `json:"routes,omitempty"`
	// Waypoints array object
	Waypoints []Waypoint `json:"waypoints,omitempty"`

	Durations    [][]float64   `json:"durations,omitempty"`    // Only for Table Request
	Distances    [][]float64   `json:"distances,omitempty"`    // Only for Table Request
	Destinations []Destination `json:"destinations,omitempty"` // Only for Table Request
	Sources      []Source      `json:"sources,omitempty"`      // Only for Table Request
	Trips        []Trip        `json:"trips,omitempty"`        // Only for Match Request
}

Main Response object

type Options

type Options struct {
	// Url of osrm server with / on the end
	Url url.URL `json:"url"`

	// One of the following values:  route ,  nearest ,  table ,  match ,  trip ,  tile
	Service string `json:"service"`

	//	Version of the protocol implemented by the service
	Version string `json:"version"`

	// Mode of transportation, is determined statically by the Lua profile that is used to prepare the data using  osrm-extract
	Profile string `json:"profile"`

	GenerateHints bool `json:"generate_hints"`

	// Timeout for request in seconds
	RequestTimeout int `json:"request_timeout"`

	// if need debug you should turn this on
	Debug bool `json:"debug"`
}

OSRM client options structure

func (*Options) BaseUrl

func (o *Options) BaseUrl() (*url.URL, error)

Gets Base url from options

type OsrmClient

type OsrmClient struct {
	Options *Options
	// contains filtered or unexported fields
}

Osrm Client Object

func NewClient

func NewClient(options *Options) *OsrmClient

NewClient creates a client with options

func (*OsrmClient) Match

func (c *OsrmClient) Match(_ *MatchRequest) (*OSRMResponse, error)

func (*OsrmClient) Nearest

func (c *OsrmClient) Nearest(_ *NearestRequest) (*OSRMResponse, error)

func (*OsrmClient) Route

func (c *OsrmClient) Route(r *RouteRequest) (*OSRMResponse, error)

func (*OsrmClient) Table

func (c *OsrmClient) Table(t *TableRequest) (*OSRMResponse, error)

type Route

type Route struct {
	Geometry   string  `json:"geometry,omitempty"`
	Legs       []Leg   `json:"legs,omitempty"`
	Distance   float64 `json:"distance,omitempty"`
	Duration   float64 `json:"duration,omitempty"`
	WeightName string  `json:"weight_name,omitempty"`
	Weight     float64 `json:"weight,omitempty"`
}

type RouteRequest

type RouteRequest struct {
	// coordinates
	Coordinates geo.PointSet `json:"coordinates"`

	// Returned route steps for each route leg
	Steps *bool `json:"steps"`

	// Search for alternative routes. Passing a number alternatives=n searches for up to  n alternative routes
	// (n not working because it bool)
	Alternatives *string `json:"alternatives"`

	// Returns additional metadata for each coordinate along the route geometry
	Annotations *string `json:"annotations"`

	// Returned route geometry format (influences overview and per step)
	Geometries *string `json:"geometries"`

	// Add overview geometry either full, simplified according to highest zoom level it could be display on, or not at all.
	Overview *string `json:"overview"`

	// Forces the route to keep going straight at waypoints constraining uturns there even if it would be faster. Default value depends on the profile.
	ContinueStraight *string `json:"continue_straight"`
}

Finds the fastest route between coordinates in the supplied order

type Source

type Source struct {
	Hint     string    `json:"hint,omitempty"`
	Name     string    `json:"name,omitempty"`
	Location []float64 `json:"location,omitempty"`
}

For Table Request

type Step

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

type TableAnnotation added in v0.1.1

type TableAnnotation string

Return the requested table or tables in response

const (
	// default
	TableAnnotationDuration         TableAnnotation = "duration"
	TableAnnotationDistance         TableAnnotation = "distance"
	TableAnnotationDurationDistance TableAnnotation = "duration,distance"
)

func (*TableAnnotation) String added in v0.1.1

func (a *TableAnnotation) String() string

type TableRequest

type TableRequest struct {
	// coordinates
	Coordinates geo.PointSet `json:"coordinates"`

	// Use location with given index as source.
	Sources *[]int `json:"sources"`

	// Use location with given index as destination.
	Destinations *[]int `json:"destinations"`

	// Returns additional metadata for each coordinate along the route geometry
	Annotations *TableAnnotation `json:"annotations"`

	//If no route found between a source/destination pair, calculate the as-the-crow-flies distance, then use this speed to estimate duration.
	FallbackSpeed *float64 `json:"fallback_speed"`

	//When using a  fallback_speed , use the user-supplied coordinate ( input ), or the snapped location ( snapped ) for calculating distances.
	FallbackCoordinate *FallbackCoordinate `json:"fallback_coordinate"`

	//Use in conjunction with  annotations=durations . Scales the table duration values by this number.
	ScaleFactor *float64 `json:"scale_factor"`
}

Computes the duration of the fastest route between all pairs of supplied coordinates

type Trip

type Trip struct {
	Geometry   string  `json:"geometry,omitempty"`
	Legs       []Leg   `json:"legs,omitempty"`
	Distance   float64 `json:"distance,omitempty"`
	Duration   float64 `json:"duration,omitempty"`
	WeightName string  `json:"weight_name,omitempty"`
	Weight     float64 `json:"weight,omitempty"`
}

For Match Request

type Waypoint

type Waypoint struct {
	Hint          string    `json:"hint,omitempty"`
	Name          string    `json:"name,omitempty"`
	Location      []float64 `json:"location,omitempty"`
	Nodes         []int     `json:"nodes,omitempty"`
	Distance      float64   `json:"distance,omitempty"`       // Nearest Request
	WaypointIndex int       `json:"waypoint_index,omitempty"` // Match Request
	TripsIndex    int       `json:"trips_index,omitempty"`    // Match Request
}

OSRM Waypoint object

Directories

Path Synopsis
examples
route command
table command

Jump to

Keyboard shortcuts

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