Fork me on GitHub

Leaflet Routing Machine API


L.Routing.Control

Combining the other classes into a full routing user interface. The main class of the plugin. Extends L.Routing.Itinerary and implements IControl.

Usage example

var map = L.map('map');

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

L.Routing.control({
    waypoints: [
        L.latLng(57.74, 11.94),
        L.latLng(57.6792, 11.949)
    ]
}).addTo(map);

Creation

Factory Description
L.Routing.control(<RoutingControlOptions> options?) Instantiates a new routing control with the provided options; unless specific router and/or plan instances are provided, options are also passed to their constructors

Options

Provides these options, in addition to the options of L.Routing.Itinerary.

Option Type Default Description
waypoints L.Routing.Waypoint[] or L.LatLng[] [] Initial waypoints for the control
router IRouter new L.Routing.OSRMv1(options) The router to use to calculate routes between waypoints
plan L.Routing.Plan new L.Routing.Plan(options.waypoints, options) The plan to use to store and edit the route’s waypoints
geocoder IGeocoder - Optional geocoder to use, unless the plan option is used
fitSelectedRoutes string/Boolean 'smart' How the map’s view is fitted to a selected route result: smart will fit only if no waypoint is within the current view, or if the result covers a very small part of the view; other truthy values will always fit the map, falsy will never fit the map
lineOptions LineOptions   Options passed when creating a new L.Routing.Line, for example styling
routeLine ``Function | - | Function to create the map line when a route is presented on the map, with the signature: fn(<[IRoute](#iroute)> route, <[LineOptions](#lineoptions)> options)`    
autoRoute Boolean true If true, route will automatically be calculated every time waypoints change, otherwise route() has to be called by the app
routeWhileDragging Boolean false If true, routes will continually be calculated while the user drags waypoints, giving immediate feedback
routeDragInterval Number 500 The minimum number of milliseconds between route calculations when waypoints are dragged
waypointMode String connect Set to either connect (waypoints are connected by a line to the closest point on the calculated route) or snap (waypoints are moved to the closest point on the calculated route)
useZoomParameter Boolean false If true, route will be recalculated when the map is zoomed
showAlternatives Boolean false If true, alternative polyline[s] will be shown on the map when available at the same time as the primary polyline
altLineOptions LineOptions   Options passed when creating a new L.Routing.Line for showing alternative line[s], when showAlternatives is set to true. If not set and showAlternatives is true, alternative lines will be styled using lineOptions

Events

Fires these events, in addition the the events used by L.Routing.Itinerary.

Event Data Description
routingstart RoutingEvent Fires when the control starts calculating a route; followed by either a routesfound or routingerror event
routesfound RoutingResultEvent One or more routes where found
routingerror RoutingErrorEvent An error occured while calculating the route between waypoints

Methods

Method Returns Description
getWaypoints() L.Routing.Waypoint[] Returns the waypoints of the control’s plan
setWaypoints(<L.Routing.Waypoint[]> waypoints \| <L.LatLng[]> latLngs) this Sets the waypoints of the control’s plan
spliceWaypoints(<Number> index, <Number> waypointsToRemove, <L.Routing.Waypoint? \| L.LatLng?>, ...) L.Routing.Waypoint[] Allows adding, removing or replacing waypoints in the control’s plan. Syntax is the same as in Array#splice. Returns the array of removed points (if any).
getPlan() L.Routing.Plan Returns the plan instance used by the control
getRouter() IRouter Returns the router used by the control
route() - Calculates the route between the current waypoints and presents in the itinerary, displaying the first result on the map

L.Routing.Itinerary

A widget to display itineraries as text in a control. Also serves as the base class for L.Routing.Control. Implements IControl.

Creation

Factory Description
L.Routing.itinerary(<ItineraryOptions> options?) Instantiates a new itinerary widget with the provided options

Options

Option Type Default Description
pointMarkerStyle Path options {radius: 5,color: '#03f',fillColor: 'white',opacity: 1,fillOpacity: 0.7} Style for the CircleMarkers used when hovering an itinerary instruction
summaryTemplate String '<h2>{name}</h2><h3>{distance}, {time}</h3>' String template to use for summarizing a route; the template is passed properties name, distance and time, where the latter two has already been processed through distanceTemplate and timeTemplate respectively
distanceTemplate String '{value} {unit}' String template to use for formatting distances as a string; passed properties value and unit
timeTemplate String '{time}' String template to use for formatting times as a string; passed property time
containerClassName String '' Class name to add for the widget’s container element
alternativeClassName String '' Class name to add to routing alternatives’ elements
minimizedClassName String '' Class name to add to minimized routing alternatives’ elements
itineraryClassName String '' Class name to add to route itinerary container
show Boolean true Display the itinerary initially; can later be changed with hide()and show() methods
formatter Formatter new L.Routing.Formatter() The formatter to use when converting itinerary instructions, distances and times to strings
itineraryFormatter ItineraryBuilder - Object used to create the DOM structure for the itinerary and its instructions. Default uses a table to hold the itinerary
collapsible Boolean undefined If true, a collapse button is added, if false, no button is added, if undefined, a button is added if the screen width is small (typically mobile devices)
collapseBtn Function   Function that takes the L.Routing.Itinerary instance as argument, and creates a collapse button
collapseBtnClass String 'leaflet-routing-collapse-btn' Class used by default for the collapse button
totalDistanceRoundingSensitivity Number -1 How much rounding should be applied to total route distance: positive values use smart rounding, where higher means more accurate, lower less accurate; negative values means fixed precision, where the number of decimals is -roundingSensitivity.

Events

Event Data Description
routeselected RouteSelectedEvent Fires when a routing alternative is selected and its itinerary is displayed

Methods

Method Returns Description
setAlternatives(<IRoute[]> alternatives) this Sets the routing alternatives to display itineraries for
hide() this Hides the itinerary control
show() this Shows the itinerary control

L.Routing.Plan

User interface to edit the plan for a route (an ordered list of waypoints). Implements ILayer.

Creation

Factory Description
L.Routing.plan(<L.Routing.Waypoint[] \| L.LatLng[]> waypoints, <PlanOptions> options?) Instantiates a new plan with given waypoint locations and options

Options

Option Type Default Description
geocoder IGeocoder - The geocoder to use (both address lookup and reverse geocoding when dragging waypoints)
addWaypoints Boolean true Can new waypoints be added by the user
draggableWaypoints Boolean true Can waypoints be dragged in the map
dragStyles Path options[] [{color: 'black', opacity: 0.15, weight: 7}, {color: 'white', opacity: 0.8, weight: 4}, {color: 'orange', opacity: 1, weight: 2, dashArray: '7,12'}] Styles used for the line or lines drawn when dragging a waypoint
maxGeocoderTolerance Number 200 Maximum distance in meters from a reverse geocoding result to a waypoint, to consider the address valid
geocoderPlaceholder Function - Function to generate placeholder text for a waypoint geocoder: placeholder(<Number> waypointIndex, <Number> numberWaypoints); by default, gives text “Start” for first waypoint, “End” for last, and “Via x” in between
geocodersClassName String '' HTML classname to assign to geocoders container
geocoderClass Function - A function that returns the HTML classname to assign to individual geocoder inputs; the function should have the signature geocoderClass(<Number> i, <Number> n), where i is the waypoint’s index, and n is the total number of waypoints in the plan
waypointNameFallback Function - When a waypoint’s name can’t be reverse geocoded, this function will be called to generate a name. Default will give a name based on the waypoint’s latitude and longitude.
createGeocoder Function - Create a geocoder for a waypoint; can take three arguments: the waypoints index (Number), the total number of waypoints (Number) and the L.Routing.Plan instance; returns an IGeocoderElement
addButtonClassName String '' HTML classname to assign to the add waypoint button
createMarker Function - Creates a marker to use for a waypoint. The function should have the signature createMarker(<Number> i, <L.Routing.Waypoint> waypoint, <Number> n), where i is the waypoint’s index, waypoint is the waypoint itself, and n is the total number of waypoints in the plan; if return value is falsy, no marker is added for the waypoint
routeWhileDragging Boolean false If true, the route is continously recalculated while waypoint markers are dragged
reverseWaypoints Boolean false If true, a button to reverse the order of the waypoints is enabled

Events

Event Data Description
waypointschanged RoutingEvent Fired when one or more waypoints change (added, deleted, moved)
waypointsspliced WaypointsSplicedEvent Also fired when waypoints changed, but includes more finegrained details on actual changes, like a call to Array.splice
waypointgeocoded GeocodingEvent Fired when a waypoint is geocoded or reverse geocoded

Methods

Method Returns Description
isReady() Boolean Returns true if the plan is ready to be routed, meaning it has at least a start and end waypoint, and both have coordinates
getWaypoints() L.Routing.Waypoint[] Returns the plan’s waypoints
setWaypoints(<L.Routing.Waypoint[]> waypoints \| <L.LatLng[]> latLngs) this Sets the plan’s waypoints
spliceWaypoints(<Number> index, <Number> waypointsToRemove, <L.Routing.Waypoint? \| L.LatLng?>, ...) L.Routing.Waypoint[] Allows adding, removing or replacing the plan’s waypoints. Syntax is the same as in Array#splice. Returns the array of removed points (if any).
createGeocoders() HTMLElement Creates and returns an HTML widget with geocoder input fields for editing waypoints by address

L.Routing.Line

Displays a route on the map, and allows adding new waypoints by dragging the line. Extends LayerGroup.

Creation

Factory Description
L.Routing.line(<IRoute> route, <LineOptions> options?) Instantiates a new line for the given route and provided options

Options

Option Type Default Description
styles Path options[] [{color: 'black', opacity: 0.15, weight: 9}, {color: 'white', opacity: 0.8, weight: 6}, {color: 'red', opacity: 1, weight: 2}] Styles used for the line or lines drawn to represent the line
addWaypoints Boolean true Can new waypoints be added by dragging the line
missingRouteStyles Path options[] [{color: 'black', opacity: 0.15, weight: 7},{color: 'white', opacity: 0.6, weight: 4},{color: 'gray', opacity: 0.8, weight: 2, dashArray: '7,12'}] Styles used for the line or lines drawn to connect waypoints to the closest point on the calculated route (the non-routable part)

Events

Event Data Description
linetouched LineTouchedEvent Fires when the line is touched (tapped or clicked)

Methods

Method Returns Description
getBounds() L.LatLngBounds Returns the bounds of the line

L.Routing.OSRMv1

Handles communication with the OSRM backend, building the request and parsing the response. Implements IRouter. Note that this class supports the OSRM HTTP API v1, that is included with OSRM version 5 and up. OSRM 4 used another API that is not supported by this class.

See OSRM HTTP API for the specification this implementation is built on.

Creation

Factory Description
L.Routing.osrmv1(<OSRMOptions> options?) Instantiates a new router with the provided options

Options

Option Type Default Description
serviceUrl String //router.project-osrm.org/viaroute Router service URL
timeout Number 30000 Number of milliseconds before a route calculation times out, returning an error to the routing callback
profile String driving The OSRM profile to use in requests
polylinePrecision Number 5 The precision to use when decoding polylines in responses from OSRM
useHints Boolean true Whether hints should be included in server requests

Methods

Method Returns Description
route(<L.Routing.Waypoint[]> waypoints, <Function> callback, <Object> context?), <RoutingOptions> options) - attempt to route through the provided waypoints, where each waypoint is an L.Routing.Waypoint. Calls callback(<IError> err?, <IRoute[]> routes?) in the provided context when done or if an error is encountered
buildRouteUrl(<L.Routing.Waypoint[]> waypoints, <RoutingOptions> options) String Returns the URL to calculate the route between the given waypoints; typically used for downloading the route in some other file format

RoutingOptions

Option Type Default Description
z Number - Current zoom level when the request was made
allowUTurns Boolean - If U-turns are allowed in this route (migh only be applicable for OSRM backend)
geometryOnly Boolean false If true, try to save bandwidth by just giving the route geometry; also, multiple results are not required (typically used for route preview when dragging a waypoint)
fileFormat String - Fileformat to return

L.Routing.Formatter

Implements functions to convert distances and times to strings, as well as converting an IInstruction to a string. Override or implement your own if you need to customize formatting.

Creation

Constructor Description
L.Routing.Formatter(<FormatterOptions> options?) Instantiates a new formatter with the provided options

Options

Option Type Default Description
language String 'en' Language to use from L.Routing.Localization
units String 'metric' Units to use; 'metric' or 'imperial'
roundingSensitivity Number 1 How much rounding should be applied to distances: positive values use smart rounding, where higher means more accurate, lower less accurate; negative values means fixed precision, where the number of decimals is -roundingSensitivity
unitNames Object {meters: 'm',kilometers: 'km',yards: 'yd',miles: 'mi',hours: 'h',minutes: 'mín',seconds: 's'} Hash of unit names to use

Methods

Method Returns Description
formatDistance(<Number> d, <Number> precision?) String Formats a distance given in meters to a string with the given (or suitable if not provided) precision and unit
formatTime(<Number> t) String Formats a time duration, given in seconds, to a string with suitable precision and unit
formatInstruction(<IInstruction> instr) String Formats an instruction to a human readable text

L.Routing.ItineraryBuilder

Creates the DOM structure for an itinerary. Subclass or reimplement to create your own itinerary structure.

Methods

Method Returns Description
createContainer(<String> className) HTMLElement Create the container in which the itinerary will be put; default will create a table
createStepsContainer(<HTMLElement> container) HTMLElement Create the container for the instructions/steps; default will create a tbody
createStep(<String> text, <String> distance, <HTMLElement> steps) HTMLElement Creates a DOM element for an instruction, with the provided text and distance (already formatted as string with unit); default will create a tr

L.Routing.Localization

Contains localization for strings used by the control. The object is a simple hash with language code as key.

L.Routing.Waypoint

property type description
latLng L.LatLng geographic location of the waypoint
name String? name of the waypoint, typically an address; optional and possibly null or undefined
options WaypointOptions? Options

Options

Option Type Default Description
allowUTurn Boolean false When using OSRM for routing, allow U-turn at this waypoint

Event Objects

RoutingEvent

property type description
waypoints L.Routing.Waypoint[] The waypoints of the related route

RoutingResultEvent

property type description
waypoints L.Routing.Waypoint[] The waypoints of the related route
routes IRoute[] The routing alternatives

RoutingErrorEvent

property type description
error IError Error object, as passed by the current IRouter

RouteSelectedEvent

property type description
route IRoute The selected route

WaypointsSplicedEvent

property type description
index Number Index of modification
nRemoved Number Number of items removed
added L.Routing.Waypoint[] Added waypoints

LineTouchedEvent

property type description
afterIndex Number Index of the waypoint closest before the location where the line was touched
latlng Number Location where the line was touched

GeocodingEvent

property type description
waypointIndex Number Index of the waypoint that was geocoded
waypoint L.Routing.Waypoint The waypoint that was geocoded

IRouter

Methods

Method Returns Description
route(<L.Routing.Waypoint[]> waypoints, <Function> callback, <Object> context?), <RoutingOptions> options) - attempt to route through the provided waypoints, where each waypoint is an L.Routing.Waypoint. Calls callback(<IError> err?, <IRoute[]> routes?) in the provided context when done or if an error is encountered

IRoute

Describes a route through a number of waypoints.

property type description
name String a descriptive name for this route
summary IRouteSummary summary of the route
coordinates L.LatLng[] an array of L.LatLngs that can be used to visualize the route; the level of detail should be high, since Leaflet will simplify the line appropriately when it is displayed
waypoints - L.LatLng[] the waypoints for this route
instructions IInstruction[] instructions for this route

IRouteSummary

property type description
totalTime Number estimated time for the route, in seconds
totalDistance Number distance for the route, in meters

IInstruction

Describes a part of a route’s itinerary, such as a turn. Can be of two types: either a text property containing the exact text to be shown to the user, a number of properties that describe the instruction in an abstract form; the latter can later be translated to different languages, while explicit text can’t.

Properties

Mandatory:

property type description
distance Number distance in meters for this segment
time Number estimated time in seconds for this segment

Combined with either:

property type description
text String explicit instruction text

or:

property type description
type String one of the enumerated instruction types (see below)
road String name of road for this segment, if available
direction String aproximate compass direction: N, NE, E, SE, S, SW, W, NW
exit Integer for roundabouts, designates the number of the exit to take

Types

IGeocoderElement

property type description
container HTMLElement The main element of the geocoder, that is added to the control
input HTMLElement Input element where the geocoder’s value can be get and set
closeButton HTMLElement Optional element which, when clicked, removes the corresponding waypoint

IError

Properties