Working with routes programmatically

Overview

Use the multiRouter.MultiRoute class to build multi-stop routes that include three or more points. You can use this class to get route information, change the route's appearance, and reverse the route points. More about route settings

Attention. Routing requests are fee-based.

Building a route on a map

To build a route using the multiRouter.MultiRoute class, create an instance of this class and add it to the map:

// Set the route.
// A driving route is created by default.
var multiRoute = new ymaps.multiRouter.MultiRoute({   
    // Route points. Points can be set as coordinates or addresses. 
    referencePoints: [
        'Smolenskaya metro station, Moscow',
        'Arbatskaya metro station, Moscow',
        [55.734876, 37.59308], // Lva Tolstogo street
    ]
}, {
      // |Automatically set the map viewport so that
      // the entire route is visible.
      boundsAutoApply: true
});

// Add the route to the map.
myMap.geoObjects.add(multiRoute);
Copied to clipboard
View the complete example code
Attention. For points that are set as a string, additional requests will be sent to the Geocoder. Each point is counted as a separate request. In addition, enabling the reverseGeocoding option will also create extra requests to the Geocoder. Remember that geocoding requests are fee-based.

By default, route points can't be moved. In order for users to be able to move, delete, and create points, editing mode must be enabled.

Route settings

You can configure various settings for the route. For example, you can switch the routing type, change the appearance, or reverse the points.

There are two ways to configure settings: when creating a route using the constructor, or via the setParams() method. The examples below show how to manage route settings.

For solutions to other common routing tasks, see Solving typical tasks.

Selecting the routing type

The routing type is set in the routingMode parameter. The following types of routing are available:
  • "auto" (default) — A driving route.
  • "masstransit" — A route on public transit.
  • "pedestrian" — A walking route.
  • "bicycle" — A bike route.

Example:

// Build a route on public transit.

// Create a route instance.
var multiRoute = new ymaps.multiRouter.MultiRoute({
    referencePoints: [
        'Smolenskaya metro station',
        'Arbatskaya metro station'
    ],
    params: {
      // Route type: on public transit.
      routingMode: "masstransit"  
    }
}, {
      // Automatically set the map viewport so that
      // the entire route is visible.
      boundsAutoApply: true
});

// Add the route to the map.
myMap.geoObjects.add(multiRoute);
Copied to clipboard
View the complete example code

You can also change the route type after the route is created:

// Alternative way to change the route type: via the setParams() method.
multiRoute.model.setParams({
    routingMode: 'bicycle'
});
Copied to clipboard

When the routingMode parameter changes, the route is re-built.

Building a route with traffic allowances

To build a route that allows for traffic, set avoidTrafficJams: true.

// Build a route that avoids traffic.
var multiRoute = new ymaps.multiRouter.MultiRoute({
    referencePoints: [
        "Park Pobedy, Moscow",
        "Losiny Island, Moscow"
    ],
    params: {
        avoidTrafficJams: true
    }
}, {
        // Automatically set the map viewport so that
        // the entire route is visible.
        boundsAutoApply: true
    });

// Add the route to the map.
myMap.geoObjects.add(multiRoute);
Copied to clipboard
View the complete example code

You can also enable or disable traffic allowances after a route has been added to the map:

// Disable traffic allowances via the setParams() method.
multiRoute.model.setParams({
    avoidTrafficJams: false
});
Copied to clipboard
When the avoidTrafficJams parameter changes, the route is recalculated.

The sandbox has an of using a button to turn traffic on and off.

Adding throughpoints

Throughpoints are set via the viaIndexes parameter. For example:
// Create a route with three points.
// The second point is a throughpoint.
var multiRoute = new ymaps.multiRouter.MultiRoute({
    referencePoints: [
      'Park Kulturi metro station',
      'Smolenskaya metro station',
      'Arbatskaya metro station'
    ],
    params: {
      // Set the second point (Smolenskaya metro station)
      // as a throughpoint.
      viaIndexes: [1]
    }
}, {
    boundsAutoApply: true
});
// Add the route to the map.
myMap.geoObjects.add(multiRoute);
Copied to clipboard
View the complete example code
Note. Throughpoints are only available for driving routes.

Customizing the appearance of the route

You can change the appearance of a route when you create it using the route constructor. Display options are passed to the constructor as the second argument:

// Create a route.
var multiRoute = new ymaps.multiRouter.MultiRoute({
    referencePoints: [
        [55.734470, 37.58000],
        [55.734336, 37.51218],
        [55.724102, 37.19912]
    ]
}, {
    // Appearance of waypoints.
    wayPointStartIconColor: "#FFFFFF",
    wayPointStartIconFillColor: "#B3B3B3",
    // Appearance of the active route path.
    routeActiveStrokeWidth: 8,
    routeActiveStrokeStyle: 'solid',
    routeActiveStrokeColor: "#002233",
    // Appearance of alternative route paths.
    routeStrokeStyle: 'dot',
    routeStrokeWidth: 3,
    boundsAutoApply: true
});
// Add the route to the map.
myMap.geoObjects.add(multiRoute);
Copied to clipboard
View the complete example code

Enabling editing mode

When a route is added to the map, editing mode is disabled — the route points are inactive and users can't move them.

To enable editing mode, use the start() method:

var multiRoute = new ymaps.multiRouter.MultiRoute({
    referencePoints: [
        "Sokol metro station, Moscow",
        "Paveletskaya metro station, Moscow"
    ]
});
// Enable editing mode.
multiRoute.editor.start();
// And then disable editing mode.
// multiRoute.editor.stop();

// Add the route to the map.
myMap.geoObjects.add(multiRoute);
Copied to clipboard
View the complete example code

Adding new points in editing mode

By default, editing mode does not allow users to create new points or delete existing ones. To make this possible, you need to specify special options:

var multiRoute = new ymaps.multiRouter.MultiRoute({
    referencePoints: [
        "Sokol metro station, Moscow",
        "Paveletskaya metro station, Moscow"
    ]
}, {
    // The editorDrawOver option forbids setting points on top of map objects
    // (when adding new points). This is necessary
    // in order for users to add intermediary
    // points on the route path.
    editorDrawOver: false,
    // The editorMidPointsType option sets the type of intermediary
    // points to create on the route.
    // "via" — throughpoints
    // "way" — waypoints
    editorMidPointsType: "via"
});

// Enable editing mode and configure settings.
multiRoute.editor.start({
    // When the addWayPoints option is enabled, users can
    // create waypoints by clicking on the map.
    addWayPoints: true,
    // When the removeWayPoints option is enabled, users can
    // delete waypoints. 
    // To delete a waypoint, double-click it.
    removeWayPoints: true,
    // When the addMidPoints option is enabled, users can
    // add new intermediary points.
    // To create an intermediary point, click and hold the route path
    // while moving the point to the desired position on the map.
    // The type of intermediary point (waypoint or throughpoint) is set in 
    // the editorMidPointsType option.
    addMidPoints: true
});

// Add the route to the map.
myMap.geoObjects.add(multiRoute);
Copied to clipboard
View the complete example code

The sandbox has an with a button to turn on editing mode.

Getting information about a route

The multiRouter.MultiRoute object contains information about created routes, including the distance and travel time, and information about closed sections of road on a driving route.

All operations with the route are listed in the reference guide.

How to get information about the active route

To get a reference to the active route, use the getActiveRoute() method. Depending on which type of routing is used, the route is described by the object:

The example below shows how to get the active route:

// Subscribe to the event for updating route data.
// To learn more about this event, see the reference guide.
// Note that the subscription is for the 'model' field.
multiRoute.model.events.add('requestsuccess', function() {
    // Get a reference to the active route.
    var activeRoute = multiRoute.getActiveRoute();
    // Output route information.
    console.log("Distance: " + activeRoute.properties.get("distance").text);
    console.log("Travel time: " + activeRoute.properties.get("duration").text);
    // For driving routes, information about 
    // closed road sections can be output.
    if (activeRoute.properties.get("blocked")) {
        console.log("The route has sections with closed roads.");    }});
Copied to clipboard
View the complete example code

How to get the route paths

The path is a section of the route between two stopping points.

To get a list of paths, use the getPaths() method. Each route path is described by an object that corresponds to the route type:

The example below shows how to get the route paths:

// Get a collection of paths for the active route.
// activeRoute is an object that describes the active route.
// It was received earlier (see the example).
var activeRoutePaths = activeRoute.getPaths();    
// Iterate a collection of paths.
activeRoutePaths.each(function(path) {
    console.log("Distance: " + path.properties.get("distance").text);
    console.log("Travel time: " + path.properties.get("duration").text);
}); 
Copied to clipboard
View the complete example code

How to get information about route segments

Each route is divided into segments. Segments are sections between:
  • Waypoints or throughpoints.
  • Points where the direction of travel may change (a fork, entrance, exit, turn, U-turn, or intersection).
  • Points where the type of route section changes. For example, the point where a “walking” segment changes to a “bus” segment.

To get a list of segments, use the getSegments() method. Each segment is described by an object that corresponds to the route type:

The example below shows how to get route segments:

// First you need to get a collection of route paths.
// Note: the activeRoute object was received earlier (see the example).
var activeRoutePaths = activeRoute.getPaths(); 
// Iterate the collection of paths.
activeRoutePaths.each(function(path) {
  // Get a collection of segments for each path.
  var segments = path.getSegments();
  // Iterate the collection of segments and output information about each segment.
  segments.each(function(segment) {
    console.log("Maneuver at end of segment: " + segment.properties.get("action").text);
    console.log("Distance: " + segment.properties.get("distance").text);
    console.log("Travel time: " + segment.properties.get("duration").text);
    console.log("Street that the segment follows: " + segment.properties.get("street"));
  }); 
});   
Copied to clipboard
View the complete example code

The sandbox has interactive examples:

  • — This example creates a public transit route. The route segments turn different colors depending on the type of segment (by bus or on foot).

  • — Displays information about route segments on an HTML page.

How to get waypoints on the route

A waypoint is a point on the route to make a stop at. The starting and ending points are also waypoints.

Waypoints are described by the multiRouter.WayPoint object. To get a list of waypoints on a route, use the getWayPoints() method.

var wayPoints = multiRoute.getWayPoints();  

// Iterate the collection of waypoints.
// For each point, set the placemark content.
wayPoints.each(function (point) {   
    point.options.set({
        preset: "islands#redStretchyIcon",
        // Set the address of the point as the placemark content.
        iconContentLayout: ymaps.templateLayoutFactory.createClass('{{ properties.request|raw }}')
    });
});    
Copied to clipboard
View the complete example code

How to get throughpoints on the route

A throughpoint is a point that the route must go through, but does not imply a stop. Throughpoints are only supported for driving routes.

Throughpoints are described by the multiRouter.ViaPoint object. To get throughpoints on a route, use the getViaPoints() method.

The example below demonstrates how to obtain information about throughpoints and set their appearance.

var viaPoints = multiRoute.getViaPoints();
// Iterate the collection of throughpoints.
viaPoints.each(function (point) { 
    // Set the appearance of each throughpoint.
    point.options.set({  
        iconRadius: 7,
        iconFillColor: "#000088",
        // The appearance of a throughpoint for the active route.
        activeIconFillColor: "#E63E92"
    }); 
});
Copied to clipboard
View the complete example code

For a more detailed example, see in the sandbox.

Solving typical tasks

How can I show the address in placemark labels?

If the route points are set by address, the addresses are automatically displayed in labels.

If the route points are set by coordinates, the reverseGeocoding option must be enabled in order for addresses to be shown in labels.

var multiRoute = new ymaps.multiRouter.MultiRoute({
    referencePoints: [
      [55.734876, 37.59308],
      [55.761184, 37.57850]
    ],
    params: {
       reverseGeocoding: true
    }
});

// Add the route to the map.
myMap.geoObjects.add(multiRoute);
Copied to clipboard
Note. The reverseGeocoding option is a flag that allows the API to perform reverse geocoding. This means that for points that are set using coordinates, the API sends requests to the Geocoder to determine their addresses. Remember that requests to the Geocoder are fee-based. When enabling the reverseGeocoding option, consider the load on your site to avoid exceeding your daily request limit.
How can I hide labels on route markers?

In order to not show addresses on labels, the route points must be set in coordinates. In addition, the reverseGeocoding option must be set to false.

var multiRoute = new ymaps.multiRouter.MultiRoute({
    referencePoints: [
      [55.734876, 37.59308],
      [55.761184, 37.57850]
    ],
    params: {
      reverseGeocoding: false
    }
});

// Add the route to the map.
myMap.geoObjects.add(multiRoute);
Copied to clipboard
How do I set my own image for placemarks?

You can set a custom placemark image in the route options. Note that you need to specify the 'wayPoint' prefix for waypoints.

var multiRoute = new ymaps.multiRouter.MultiRoute({
  referencePoints: [
    "Leninsky Prospekt, Moscow",
    "16 Lva Tolstogo, Moscow",
    "Sokolniki Park, Moscow"
  ]
}, {
  // Set a custom image
  // for the ending point.
  wayPointFinishIconLayout: "default#image",
  wayPointFinishIconImageHref: "images/img.png",
  wayPointFinishIconImageSize: [30, 30],
  wayPointFinishIconImageOffset: [-15, -15]
 });

// Add the route to the map.
myMap.geoObjects.add(multiRoute);
Copied to clipboard

I need to change the route's appearance on hover. How do I do that?

The example below shows how to change the color of the route path when the mouse pointer hovers over it. The active route is black, and alternative routes are white.

var multiRoute = new ymaps.multiRouter.MultiRoute({
    referencePoints: [
      [55.734470, 37.58000],
      [55.734336, 37.51218],
      [55.724102, 37.19912]
    ]
}, {
    boundsAutoApply: true
});

// Subscribe to the route display readiness event. 
multiRoute.events.add('update', function() {
    // Get a list of created routes.
    var routes = multiRoute.getRoutes();
    // Iterate the collection of routes.
    // For each route, subscribe to the
    // 'mouseenter' and 'mouseleave' events.
    routes.each(function(route) {
        route.events.add('mouseenter', function() {
           // Get a reference to the active route.
           var active = multiRoute.getActiveRoute();
            route.options.set('strokeWidth', 10);
            // The active route will be black.
            if (active === route) {
                route.options.set('strokeColor', "#000000");
            } else {
                route.options.set('strokeColor', "#FFFFFF");
            }
        });
        route.events.add('mouseleave', function() {
            route.options.unset('strokeWidth');
            route.options.unset('strokeColor');
        });
    });  
});

// Add the route to the map.
myMap.geoObjects.add(multiRoute);  
Copied to clipboard
  • The sandbox has another example: . In the example, the route segments are different colors depending on the type of segment (bus or subway).

How do I set a custom route balloon layout?

See the .

How can I make sure that the map boundaries are automatically redrawn every time the route changes?

To do this, subscribe to the 'boundschange' route event. In the event handler, set the checkZoomRange option to true.

multiRoute.events.add("boundschange", function() {
    myMap.setBounds(multiRoute.getBounds(), {
        checkZoomRange: true
    });
});
Copied to clipboard
Note. You can also set automatic map centering via the boundsAutoApply option. However, this option only centers the map when the route is first built.
How can I remove the placemarks on waypoints?

Method 1: Use the wayPointVisible option:

var multiRoute = new ymaps.multiRouter.MultiRoute({
    referencePoints: [
      [55.734876, 37.59308],
      [55.761184, 37.57850]
    ]
}, {
    wayPointVisible: false,
    boundsAutoApply: true
});

// Add the route to the map.
myMap.geoObjects.add(multiRoute);
Copied to clipboard

However, in this case the route points will be inactive and users will not be able to move them.

Method 2: Set a custom image for the placemark that will be less noticeable. Example of setting a custom image:

// Create a route.
var multiRoute = new ymaps.multiRouter.MultiRoute({
    referencePoints: [
        "Leninsky Prospekt, Moscow",
        "16 Lva Tolstogo, Moscow",
        "Vodny Stadion metro station, Moscow"
    ]
}, {
    // Set the appearance of the starting point.
    wayPointStartIconLayout: "default#image",
    wayPointStartIconImageHref: "images/myImageStart.png",
    wayPointStartIconImageSize: [10, 10],
    wayPointStartIconImageOffset: [-5, -5],
    // Set the appearance of the ending point.
    wayPointFinishIconLayout: "default#image",
    wayPointFinishIconImageHref: "images/myImageFinish.png",
    wayPointFinishIconImageSize: [10, 10],
    wayPointFinishIconImageOffset: [-5, -5],
    // Set the appearance of the intermediary point.
    wayPointIconLayout: "default#image",
    wayPointIconImageHref: "images/myImageWayPoint.png",
    wayPointIconImageSize: [10, 10],
    wayPointIconImageOffset: [-5, -5],
    boundsAutoApply: true
});

// Add the route to the map.
myMap.geoObjects.add(multiRoute);
Copied to clipboard
How can I get information about a route's distance and travel time?

See the in the sandbox.

How can I get information about route segments on public transport?
// Build a route with three points.
var multiRoute = new ymaps.multiRouter.MultiRoute({
    // Define the multiroute reference points.
    referencePoints: [
        [55.734876, 37.59308],
        "Mytishi, Moscow"
    ],
    params: {
        routingMode: "masstransit"
    }
});

// Show the route on the map.
myMap.geoObjects.add(multiRoute);

multiRoute.events.add('update', function() {
    // Get the active route.
    var activeRoute = multiRoute.getActiveRoute();
    // Get the paths for the active route.
    var activeRoutePaths = activeRoute.getPaths();
    
    // Iterate the collection of route paths.
    activeRoutePaths.each(function(path) {
        // Get the route segments.
        var segments = path.getSegments();
        // Iterate the collection of route segments.
        segments.each(function(segment) {
            // Segment type (walking or on public transit).
            var segmentType = segment.properties.get("type");
            // Get all the "On public transit" segments.
            var segmentTransports = segment.properties.get('transports');
            if (segmentTransports != undefined) {
                segmentTransports.forEach(function(transport) {
                    console.log("Route number or direction: " + transport.name);
                    console.log("Transit type: " + transport.type);
                    console.log("Color: " + transport.Style); // Color of the subway line.
                });            }        });    });});
Copied to clipboard

The sandbox has another example: . In the example, the route segments are different colors depending on the type of segment (bus or subway).

How can I count the number of transfers on the subway?
var multiRoute = new ymaps.multiRouter.MultiRoute({
    // Define the multiroute's reference points.
    referencePoints: [
        "Park Pobedy metro station, Moscow",
        "Babushkinskaya metro station, Moscow"
    ],
    params: {
        routingMode: "masstransit"
    }
});

// Show the route on the map.
myMap.geoObjects.add(multiRoute);

multiRoute.events.add('update', function() {
    var activeRoute = multiRoute.getActiveRoute();
    // Travel time for the route.
    var activeRouteDuration = activeRoute.properties.get("duration").text;
    // Get the route paths.
    var activeRoutePaths = activeRoute.getPaths();
    
    var transferCount = 0;

    activeRoutePaths.each(function(path) {
        var segments = path.getSegments(); 
        segments.each(function (segment) {
            var segmentType = segment.properties.get("type");
            // If the segment type is transfer, add one to the counter total.
            if (segmentType == "transfer") {
                transferCount += 1;
            }
        });   
    });
    console.log("Number of subway transfers: " + transferCount); 
    console.log("Travel time: " + activeRouteDuration); 
});
Copied to clipboard
How do I edit a route programmatically (add or remove points, change the routing type, and so on)?

To programmatically edit the route, use the multiRoute.model field:

// Create a route instance.
var multiRoute = new ymaps.multiRouter.MultiRoute({
    referencePoints: [
        'Arbatskaya metro station', 
        'Smolenskaya metro station'               
    ]
});

// Add the route to the map.
myMap.geoObjects.add(multiRoute);

// Recalculate the route for the new points. 
// The 'Arbatskaya metro station' point will be removed from the route.
multiRoute.model.setReferencePoints([ 
    'Smolenskaya metro station',
    'Tekstilshiki metro station'
]);

// Change routing parameters.
multiRoute.model.setParams({
    routingMode: 'masstransit'
});
Copied to clipboard