navitia

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2021 License: Unlicense Imports: 14 Imported by: 0

README

navitia is a Go client for the navitia API for public transit & transportation

Build Status Go Report Card GoDoc

This is govitia/navitia golang API.

Dependencies

  • It needs at least go 1.7 to work as we use context & tests use testing.T.Run for subtests.
  • The dependencies are directly pulled in by go get, but for you

Install

go get -u github.com/govitia/navitia

Coverage

  • Coverage [/coverage]: You can easily navigate through regions covered by navitia.io, with the coverage api. The shape of the region is provided in GeoJSON, though this is not yet implemented. (navitia.io doc)
  • Journeys [/journeys]: This computes journeys or isochrone tables. (navitia.io doc)
  • Places [/places]: Allows you to search in all geographical objects using their names, returning a list of places. (navitia.io doc)

Changelog

Changelog

Contributing

Contributing guide

Getting started

Creating a new session

First, you should have an API key from navitia.io, if you don't already have one, it's this way !

session, err := navitia.New(APIKEY)
Finding places
import(
	"github.com/govitia/navitia"
	"github.com/govitia/navitia/types"
	"context"
)

// Create a request
req := navitia.PlacesRequest{
	Query: "10 rue du caire, Paris",
	Types: []string{"address"},
	Count: 1,
}

// Execute it
res, _ := session.Places(context.Background(),req)

// Create a variable to store it
var myPlace types.Place

// Check if there are enough results, and then assign the first element as your place
if places := res.Places; len(places) != 0 {
	myPlace = res.Places
}
Calculating a journey
import(
	"github.com/govitia/navitia"
	"fmt"
	"context"
)

// Create a request, having already found two corresponding places
request := navitia.JourneyRequest{
	From: myPlace,
	To: thatOtherPlace,
}

// Execute it
res, _ := session.Journeys(context.Background(),request)

// Print it (JourneysResults implements Stringer)
fmt.Println(res)
Paging

Unfortunately, paging isn't supported by Regions nor by Places requests. You'll have to play with the PlacesRequest.Count value in the latter case. We'll use a Journey to showcase the paging:


// Obtain a journey like last time...

// Create a value to store the paginated result
var paginated *JourneyResults = res

// Iterate by checking if the Paging.Next function is not nil !
for paginated.Paging.Next != nil {
	// Create a new JourneyResults to hold the data
	p := JourneyResults{}
	
	// Call the function
	_ = paginated.Paging.Next(ctx, testSession, &p)

	// Assign a pointer to the previously created data structure to paginated
	paginated = &p
}

Obviously, you'll want to stop paginating at some point, and most importantly do something with the value. An example is on the way !

Scoping

When you wish to make some requests requiring a specific coverage, or have more meaningful results in global requests, you create a Scope

import (
	"github.com/govitia/navitia"
	"github.com/govitia/navitia/types"
	"context"
)

var (
	session *navitia.Session
	regionID types.ID
	req navitia.PlacesRequest
)

scope := session.Scope(regionID)

// Requests places in this scope
res, _ := scope.Places(context.Background(),req)
Going further

Obviously, this is a very simple example of what navitia can do, check out the documentation !

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Connection

type Connection struct {
	Display   types.Display
	StopPoint types.StopPoint
	Route     types.Route
}

A Connection is either a Departure or an Arrival

type ConnectionsRequest

type ConnectionsRequest struct {
	// From what time on do you want to see the results ?
	From time.Time

	// Maximum duration between From and the retrieved results (default 24h)
	Duration time.Duration

	// The maximum amount of results (default 10)
	Count uint

	// ForbiddenURIs
	Forbidden []types.ID

	// Freshness of the data
	Freshness types.DataFreshness

	// Enables GeoJSON data in the reply. GeoJSON objects can be VERY large ! >1MB.
	Geo bool
}

ConnectionsRequest contains the optional parameters for a Departures request.

type ConnectionsResults

type ConnectionsResults struct {
	Connections []Connection
	Paging      Paging `json:"links"`
	Logging     `json:"-"`
}

ConnectionsResults holds the results of a departures or arrivals request.

func (*ConnectionsResults) UnmarshalJSON

func (cr *ConnectionsResults) UnmarshalJSON(b []byte) error

UnmarshalJSON implements unmarshalling for ConnectionsResults.

type DeparturesRequest

type DeparturesRequest struct {
	StopArea string
}

DeparturesRequest contain the parameters needed to make a departures

type DeparturesResults

type DeparturesResults struct {
	Departures []types.Departure `json:"departures"`
	Paging     Paging            `json:"links"`
	Logging    `json:"-"`
	// contains filtered or unexported fields
}

func (*DeparturesResults) Count

func (dr *DeparturesResults) Count() int

Count returns the number of results available in a Departures

type JourneyRequest

type JourneyRequest struct {
	// There must be at least one From or To parameter defined
	// When used with just one of them, the resulting Journey won't have a populated Sections field.
	From types.ID
	To   types.ID

	// When do you want to depart ? Or is DateIsArrival when do you want to arrive at your destination.
	Date          time.Time
	DateIsArrival bool

	// The traveller's type
	Traveler types.TravelerType

	// Define the freshness of data to use to compute journeys
	Freshness types.DataFreshness

	// Forbidden public transport objects
	Forbidden []types.ID

	// Allowed public transport objects
	// Note: This counstraint intersects with Forbidden
	Allowed []types.ID

	// Force the first section mode if it isn't a public transport mode
	// Note: The parameter is inclusive, not exclusive. As such if you want to forbid a mode you have to include all modes except that one.
	FirstSectionModes []string

	// Same, but for the last section
	LastSectionModes []string

	// MaxDurationToPT is the maximum allowed duration to reach the public transport.
	// Use this to limit the walking/biking part.
	MaxDurationToPT time.Duration

	// These four following parameters set the speed of each mode (Walking, Bike, BSS & car)
	// In meters per second
	WalkingSpeed   float64
	BikeSpeed      float64
	BikeShareSpeed float64
	CarSpeed       float64

	// Minimum and maximum amounts of journeys suggested
	MinJourneys uint
	MaxJourneys uint

	// Count fixes the amount of journeys to be returned, overriding minimum & maximum amount
	// Note: if Count=0 then it isn't taken into account
	Count uint

	// Maximum number of transfers in each journey
	MaxTransfers uint

	// Maximum duration of a trip
	MaxDuration time.Duration // To seconds

	// Wheelchair restricts the answer to accessible public transports
	Wheelchair bool

	// Headsign If given, add a filter on the vehicle journeys that has the
	// given value as headsign (on vehicle journey itself or at a stop time).
	Headsign string
}

JourneyRequest contain the parameters needed to make a Journey request

type JourneyResults

type JourneyResults struct {
	Journeys []types.Journey `json:"journeys"`
	Paging   Paging          `json:"links"`
	Logging  `json:"-"`
	// contains filtered or unexported fields
}

JourneyResults contains the results of a Journey request. Warning: types.Journey.From / types.Journey.To aren't guaranteed to be filled. Based on very basic inspection, it seems they aren't filled when there are sections...

func (*JourneyResults) Count

func (jr *JourneyResults) Count() int

Count returns the number of results available in a JourneyResults

type Logging

type Logging struct {
	Created  time.Time
	Sent     time.Time
	Received time.Time
}

Logging stores logging info

type Paging

type Paging struct {
	// Next results
	Next func(ctx context.Context, s *Session, res results) error

	// Previous results
	Previous func(ctx context.Context, s *Session, res results) error
}

Paging holds potential Previous / Next functions

func (*Paging) UnmarshalJSON

func (p *Paging) UnmarshalJSON(b []byte) error

UnmarshalJSON unmarshals a Paging type from a Links data structure

type PlacesRequest

type PlacesRequest struct {
	Query string // The search item

	// Types are the type of objects to query
	// It can either be a stop_area, an address, a poi or an administrative_region
	Types []string

	// If given it will filter the search by specific admin uris
	AdminURI []string

	// Enables GeoJSON data in the reply. GeoJSON objects can be VERY large ! >1MB.
	Geo bool

	// If given, it will prioritise objects around these coordinates
	Around types.Coordinates

	// Maximum amount of results
	Count uint
}

PlacesRequest is the query you need to build before passing it to Places

type PlacesResults

type PlacesResults struct {
	Places []types.Container `json:"places"`

	Logging `json:"-"`
	// contains filtered or unexported fields
}

PlacesResults doesn't have pagination, as the remote API doesn't support it. PlacesResults can be sorted, it implements sort.Interface.

func (*PlacesResults) Len

func (pr *PlacesResults) Len() int

Len is the number of Places in the results.

func (*PlacesResults) Less

func (pr *PlacesResults) Less(i, j int) bool

Less reports if the quality of the Place with the index i is less than that of the Place with the index j Note: In most use cases, that's the opposite of the desired behaviour, so simply use sort.Reverse and ta-da !

func (*PlacesResults) Swap

func (pr *PlacesResults) Swap(i, j int)

Swap swaps the Place of index i and the Place of index j

type RegionRequest

type RegionRequest struct {
	// Count is the number of items to return, if count=0, then it will return the default number
	// BUG: Count doesn't work, server-side.
	Count uint

	// Enables Geo data (in MKT format) in the reply. Geo objects can be large and slower to parse.
	Geo bool
}

RegionRequest contains the parameters needed to make a Coverage request

type RegionResults

type RegionResults struct {
	// The list of regions retrieved
	Regions []types.Region `json:"Regions"`

	// Timing information
	Logging
	// contains filtered or unexported fields
}

A RegionResults holds results for a coverage query This Results doesn't support paging :(

type RemoteError

type RemoteError struct {
	StatusCode int
	ID         RemoteErrorID `json:"id"`
	Message    string        `json:"message"`
}

A RemoteError represents an error sent by the server

func (RemoteError) Error

func (err RemoteError) Error() string

Error formats the error in a human-readable format Also allows it to satisfy the error interface

type RemoteErrorID

type RemoteErrorID string

RemoteErrorID is an ID for a remote error

const (
	RemoteErrDateOutOfBounds       RemoteErrorID = "date_out_of_bounds"         // When the given date is out of bounds of the production dates of the region
	RemoteErrNoOrigin              RemoteErrorID = "no_origin"                  // Couldn’t find an origin for the journeys
	RemoteErrNoDestination         RemoteErrorID = "no_destination"             // Couldn’t find an destination for the journeys
	RemoteErrNoOriginNoDestination RemoteErrorID = "nor_origin_nor_destination" // Couldn’t find an origin nor a destination for the journeys
	RemoteErrUnknownObject         RemoteErrorID = "unknown_object"             // Unknown Object

	RemoteErrBadFilter     RemoteErrorID = "bad_filter"      // Bad filter (with custom filter)
	RemoteErrUnableToParse RemoteErrorID = "unable_to_parse" // Unable to parse mal-formed custom filter"
)

RemoteErrXXX are the known error ids that can be returned by the navitia server

type Scope

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

A Scope is a coverage-scoped question, allowing you to query information about a specific region.

It is needed for every non-global request you wish to make, and helps have better results with some global request too!

func (*Scope) ArrivalsSA

func (scope *Scope) ArrivalsSA(ctx context.Context, req ConnectionsRequest, resource types.ID) (*ConnectionsResults, error)

ArrivalsSA requests the arrivals for a given StopArea in a given region.

func (*Scope) ArrivalsSP

func (scope *Scope) ArrivalsSP(ctx context.Context, req ConnectionsRequest, resource types.ID) (*ConnectionsResults, error)

ArrivalsSP requests the arrivals for a given StopPoint in a given region.

func (*Scope) Departures

func (scope *Scope) Departures(ctx context.Context, req DeparturesRequest) (*DeparturesResults, error)

Departures computes a list of Departures according to the parameters given in a specific scope

func (*Scope) DeparturesSA

func (scope *Scope) DeparturesSA(ctx context.Context, req ConnectionsRequest, resource types.ID) (*ConnectionsResults, error)

DeparturesSA requests the departures for a given StopArea

func (*Scope) DeparturesSP

func (scope *Scope) DeparturesSP(ctx context.Context, req ConnectionsRequest, resource types.ID) (*ConnectionsResults, error)

DeparturesSP requests the departures for a given StopPoint

func (*Scope) Journeys

func (scope *Scope) Journeys(ctx context.Context, req JourneyRequest) (*JourneyResults, error)

Journeys computes a list of journeys according to the parameters given in a specific scope

func (*Scope) Places

func (scope *Scope) Places(ctx context.Context, params PlacesRequest) (*PlacesResults, error)

Places searches in all geographical objects within a coverage using their names, returning a list of places. It is context aware.

func (*Scope) VehicleJourneys

func (scope *Scope) VehicleJourneys(ctx context.Context, req VehicleJourneyRequest) (*VehicleJourneyResults, error)

VehicleJourneys computes a list of VehicleJourneys according to the parameters given in a specific scope

type Session

type Session struct {
	APIKey string
	APIURL string
	// contains filtered or unexported fields
}

Session holds a current session, it is thread-safe

func New

func New(key string) (*Session, error)

New creates a new session given an API Key. It acts as a convenience wrapper to NewCustom.

Warning: No Timeout is indicated in the default http client, and as such, it is strongly advised to use NewCustom with a custom *http.Client !

func NewCustom

func NewCustom(key, url string, client *http.Client) (*Session, error)

NewCustom creates a custom new session given an API key, URL to api base & http client

func (*Session) ArrivalsC

ArrivalsC requests the arrivals from a point described by coordinates.

func (*Session) Departures

func (s *Session) Departures(ctx context.Context, req DeparturesRequest) (*DeparturesResults, error)

Departures computes a list of Departures according to the parameters given

func (*Session) DeparturesC

func (s *Session) DeparturesC(ctx context.Context, req ConnectionsRequest, coords types.Coordinates) (*ConnectionsResults, error)

DeparturesC requests the departures from a point described by coordinates.

func (*Session) Journeys

func (s *Session) Journeys(ctx context.Context, req JourneyRequest) (*JourneyResults, error)

Journeys computes a list of journeys according to the parameters given

func (*Session) Places

func (s *Session) Places(ctx context.Context, params PlacesRequest) (*PlacesResults, error)

Places searches in all geographical objects using their names, returning a list of corresponding places. It is context aware.

func (*Session) RegionByID

func (s *Session) RegionByID(ctx context.Context, req RegionRequest, id types.ID) (*RegionResults, error)

RegionByID provides information about a specific region. If the ID provided isn't an ID of a region, this WILL fail. It is context aware.

func (*Session) RegionByPos

func (s *Session) RegionByPos(ctx context.Context, req RegionRequest, coords types.Coordinates) (*RegionResults, error)

RegionByPos provides information about the region englobing the specific position. It is context aware.

func (*Session) Regions

func (s *Session) Regions(ctx context.Context, req RegionRequest) (*RegionResults, error)

Regions lists the areas covered by the Navitia API. i.e it returns the coverage of the API. It is context aware.

func (*Session) Scope

func (s *Session) Scope(region types.ID) *Scope

Scope creates a coverage-scoped session given a region ID.

func (*Session) VehicleJourneys

func (s *Session) VehicleJourneys(ctx context.Context, req VehicleJourneyRequest) (*VehicleJourneyResults, error)

VehicleJourneys computes a list of VehicleJourneys according to the parameters given

type VehicleJourneyRequest

type VehicleJourneyRequest struct {
	ID types.ID
	// There must be at least one From or To parameter defined
	// When used with just one of them, the resulting Journey won't have a populated Sections field.
	From types.ID
	To   types.ID

	// When do you want to depart ? Or is DateIsArrival when do you want to arrive at your destination.
	Date          time.Time
	DateIsArrival bool

	// The traveller's type
	Traveler types.TravelerType

	// Define the freshness of data to use to compute journeys
	Freshness types.DataFreshness

	// Forbidden public transport objects
	Forbidden []types.ID

	// Allowed public transport objects
	// Note: This counstraint intersects with Forbidden
	Allowed []types.ID

	// Force the first section mode if it isn't a public transport mode
	// Note: The parameter is inclusive, not exclusive. As such if you want to forbid a mode
	// you have to include all modes except that one.
	FirstSectionModes []string

	// Same, but for the last section
	LastSectionModes []string

	// MaxDurationToPT is the maximum allowed duration to reach the public transport.
	// Use this to limit the walking/biking part.
	MaxDurationToPT time.Duration

	// These four following parameters set the speed of each mode (Walking, Bike, BSS & car)
	// In meters per second
	WalkingSpeed   float64
	BikeSpeed      float64
	BikeShareSpeed float64
	CarSpeed       float64

	// Minimum and maximum amounts of journeys suggested
	MinJourneys uint
	MaxJourneys uint

	// Count fixes the amount of journeys to be returned, overriding minimum & maximum amount
	// Note: if Count=0 then it isn't taken into account
	Count uint

	// Maximum number of transfers in each journey
	MaxTransfers uint

	// Maximum duration of a trip
	MaxDuration time.Duration // To seconds

	// Wheelchair restricts the answer to accessible public transports
	Wheelchair bool

	// Headsign If given, add a filter on the vehicle journeys that has the
	// given value as headsign (on vehicle journey itself or at a stop time).
	Headsign string

	// Since If given, filter on a period, optional.
	Since time.Time
	// Until, like Since, filter on a period, optional too.
	Until time.Time
}

VehicleJourneyRequest contain the parameters needed to make a Journey request

type VehicleJourneyResults

type VehicleJourneyResults struct {
	VehicleJourneys []types.VehicleJourney `json:"vehicle_journeys"`

	Disruptions []types.Disruption `json:"disruptions"`

	Paging Paging `json:"links"`

	Logging `json:"-"`
	// contains filtered or unexported fields
}

JourneyResults contains the results of a Journey request

Warning: types.Journey.From / types.Journey.To aren't guaranteed to be filled. Based on very basic inspection, it seems they aren't filled when there are sections...

func (*VehicleJourneyResults) Count

func (jr *VehicleJourneyResults) Count() int

Count returns the number of results available in a JourneyResults

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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