gosrm

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2021 License: MIT Imports: 12 Imported by: 0

README

GOSRM - GO Client for OSRM

Build Status Go 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 (
	// Version of lib
	Version = "0.2.0"

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

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

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

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

	// ServiceTrip 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"

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

	// ProfileDriving Standard profile
	ProfileDriving = "driving"

	// ProfileCar Car profile
	ProfileCar = "car"

	// ProfileFoot Foot profile
	ProfileFoot = "foot"

	// VersionFirst 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",
}

RespCode 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 Client added in v0.2.0

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

Client is an Osrm Client

func NewClient

func NewClient(options *Options) *Client

NewClient creates a client with options

func (*Client) Match added in v0.2.0

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

func (*Client) Nearest added in v0.2.0

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

func (*Client) Route added in v0.2.0

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

func (*Client) Table added in v0.2.0

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

type Destination

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

For Table Request

type Error added in v0.2.0

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

func NewGOSRMError added in v0.1.0

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

func (*Error) Error added in v0.2.0

func (e *Error) Error() string

type FallbackCoordinate added in v0.1.1

type FallbackCoordinate string

Return the requested table or tables in response

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

func (*FallbackCoordinate) String added in v0.1.1

func (a *FallbackCoordinate) String() 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

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

	//	Version of the protocol implemented by the service
	Version string

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

	// Timeout for request in seconds
	RequestTimeout int

	// if need debug you should turn this on
	Debug bool

	// if true http client uses AcceptEncoding gzip
	UseGzip bool

	ClientMaxIdleConnections  *int
	ClientTLSHandshakeTimeout *time.Duration
}

Options GOSRM client options structure

func (*Options) BaseUrl

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

BaseUrl Gets Base url from options

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"`

	// Adds a Hint to the response which can be used in subsequent requests
	GenerateHints *bool `json:"generate_hints"`
}

RouteRequest 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

TableAnnotation Return the requested table or tables in response

const (
	TableAnnotationDuration         TableAnnotation = "duration" // default
	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"`

	// Adds a Hint to the response which can be used in subsequent requests
	GenerateHints *bool `json:"generate_hints"`
}

TableRequest 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