Routing Plugin for Leaflet

The Routing Plugin for Leaflet makes it easy to send requests to the MapQuest Directions API Web Service, receive the results, and display the result on a map. If you are new to the MapQuest Plugins for Leaflet, you'll want to look at the Getting Started section in the Leaflet Plugins documentation. In order to use the Routing Plugin, you will need to include the Maps Plugin library and the Leaflet library and associated CSS files.

Getting Started

This documentation assumes that you have basic knowledge of Leaflet. To begin using the MapQuest plugins for Leaflet, you must first add the following to the head section of your page: This will load the core Leaflet library and CSS:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.js"></script>

Next, load the MapQuest Maps plugin for Leaflet and MapQuest Geocoding plugin for Leaflet and replace KEY with your API key.

<script src="https://www.mapquestapi.com/sdk/leaflet/v2.2/mq-map.js?key=KEY"></script>
<script src="https://www.mapquestapi.com/sdk/leaflet/v2.2/mq-routing.js?key=KEY"></script>

Basic Routing with Single-Line Addresses

The following example shows how to easily create a route between locations that are formatted as single-line addresses and display the route on the map.

 

The following JavaScript code creates a map, generates a route between the specified locations, and displays the route on the map.

var map,
  dir;

map = L.map('map', {
  layers: MQ.mapLayer(),
  center: [ 38.895345, -77.030101 ],
  zoom: 15
});

dir = MQ.routing.directions();

dir.route({
  locations: [
    '1600 pennsylvania ave, washington dc',
    '935 pennsylvania ave, washington dc'
  ]
});

map.addLayer(MQ.routing.routeLayer({
  directions: dir,
  fitBounds: true
}));

In the body of the page, create the 'map' element, which is where the map will appear:

<div id="map"></div>

Try It Now Try It On JSFiddle

Routing With an Advanced Location Object

The following example shows how to generate routes between locations formatted as an advanced Location object -- which is also known as 5-box format -- as well as latitude and longitude coordinates and display the results on the map.

 

The following JavaScript code creates a map, generates a route between the specified locations, and displays the route on the map.

var map,
  dir;

map = L.map('map', {
  layers: MQ.mapLayer(),
  center: [ 38.895345, -77.030101 ],
  zoom: 15
});

dir = MQ.routing.directions();

dir.route({
  locations: [
    { latLng: { lat: 38.895211, lng: -77.036495 } },
    { street: '935 pennsylvania ave', city: 'washington', state: 'dc' }
  ]
});

map.addLayer(MQ.routing.routeLayer({
  directions: dir,
  fitBounds: true
}));

In the body of the page, create the 'map' element, which is where the map will appear.

<div id="map"></div>

Try It Now Try It On JSFiddle

Routing with Multiple Locations

The following example shows how to easily generate a route using multiple locations in the route request. The result is then displayed on the map.

 

The following JavaScript code creates a map, generates a route between the specified locations, and displays the route on the map.

var map,
  dir;

map = L.map('map', {
  layers: MQ.mapLayer(),
  center: [ 42.346353, -71.415958 ],
  zoom: 9
});

dir = MQ.routing.directions();

dir.route({
  locations: [
    'worcester ma',
    { latLng: { lat: 42.346797, lng: -71.547966 }},
    { city: 'boston', state: 'ma' }
  ]
});

map.addLayer(MQ.routing.routeLayer({
  directions: dir,
  fitBounds: true
}));

In the body of the page, create the 'map' element, which is where the map will appear:

<div id="map"></div>

Try It Now Try It On JSFiddle

Route Options

The following example shows how to calculate a route using the advanced routing options that are offered in the Directions API. This example calculates a route that avoids toll roads.

 

The following JavaScript code creates a map, generates a route that avoids toll roads, and adds the route to the map.

var map,
  dir;

map = L.map('map', {
  layers: MQ.mapLayer(),
  center: [ 39.71102, -104.722557 ],
  zoom: 9
});

dir = MQ.routing.directions();

dir.route({
  locations: [
    'parker co',
    '8500 pena blvd denver co'
  ],
  options: { avoids: ['toll road'] }
});

map.addLayer(MQ.routing.routeLayer({
  directions: dir,
  fitBounds: true
}));

In the body of the page, create the 'map' element, which is where the map will appear:

<div id="map"></div>

Try It Now Try It On JSFiddle

Optimized Routing

The following example shows how to generate an optimized route and add the route to the map. The origin and destination locations of an optimized route will always remain fixed. However,the intermediate locations will automatically be re-ordered to help find the most optimal path.

For example, rather than having a route take you from Syracuse, NY to Springfield, MA, back to Ithaca, NY, and then to Hartford, CT, the optimized route will know to go from Syracuse to Ithaca first, then Springfield, and finish in Hartford.

 

 

The following JavaScript code creates a map, calculates the optimized route, and adds the result to the map:

var map,
  dir;

map = L.map('map', {
  layers: MQ.mapLayer(),
  center: [ 42.658694, -73.602323 ],
  zoom: 7
});

dir = MQ.routing.directions();

dir.optimizedRoute({
  locations: [
    'syracuse ny',
    'springfield ma',
    'ithaca ny',
    'hartford ct'
  ]
});

map.addLayer(MQ.routing.routeLayer({
  directions: dir,
  fitBounds: true
}));

In the body of the page, create the 'map' element, which is where the map will appear:

<div id="map"></div>

Try It Now Try It On JSFiddle

Route Narrative

The following example shows how to generate a route and display the route narrative. By default, the narrative for the route will be returned in the response, but it is up to the developer to display the narrative.

 
 

The following JavaScript code creates a map, calculates a route, displays the result on the map, and displays the narrative below the map:

var map,
dir;

map = L.map('map', {
    layers: MQ.mapLayer(),
    center: [ 40.045049, -105.961737 ],
    zoom: 9
});

dir = MQ.routing.directions()
    .on('success', function(data) {
        var legs = data.route.legs,
            html = '',
            maneuvers,
            i;

        if (legs && legs.length) {
            maneuvers = legs[0].maneuvers;

            for (i=0; i < maneuvers.length; i++) {
                html += (i+1) + '. ';
                html += maneuvers[i].narrative + '
'; } L.DomUtil.get('route-narrative').innerHTML = html; } }); dir.route({ locations: [ '80217', 'steamboat springs co' ] }); map.addLayer(MQ.routing.routeLayer({ directions: dir, fitBounds: true }));

In the body of the page, create the 'map' element, which is where the map will appear:

<div id="map"></div>

In order to display the route narrative, create the 'route-narrative' element, which is where the narrative will appear:

<div id="route-narrative"></div>

Try It Now Try It On JSFiddle

Start and End Marker Customization

The following example shows how to generate a route and then customize the start and end markers along the route

 
var map = L.map('map', {
    layers: MQ.mapLayer(),
    center: [40.731701, -73.993411],
    zoom: 12
});

var dir = MQ.routing.directions();

dir.route({
    locations: [
        'wood-ridge, nj',
        'staten island, ny',
        'queens, ny'
    ]
});

CustomRouteLayer = MQ.Routing.RouteLayer.extend({
    createStartMarker: function (location, stopNumber) {
        var custom_icon;
        var marker;

        custom_icon = L.icon({
            iconUrl: 'https://www.mapquestapi.com/staticmap/geticon?uri=poi-red_1.png',
            iconSize: [20, 29],
            iconAnchor: [10, 29],
            popupAnchor: [0, -29]
        });

        marker = L.marker(location.latLng, {icon: custom_icon}).addTo(map);

        return marker;
    },

    createEndMarker: function (location, stopNumber) {
        var custom_icon;
        var marker;

        custom_icon = L.icon({
            iconUrl: 'https://www.mapquestapi.com/staticmap/geticon?uri=poi-blue_1.png',
            iconSize: [20, 29],
            iconAnchor: [10, 29],
            popupAnchor: [0, -29]
        });

        marker = L.marker(location.latLng, {icon: custom_icon}).addTo(map);

        return marker;
    }
});

map.addLayer(new CustomRouteLayer({
    directions: dir,
    fitBounds: true
}));

In the body of the page, create the 'map' element, which is where the map will appear:

<div id="map"></div>

Try It Now Try It On JSFiddle

Route Customization with Clickable POI Markers

In addition to calculating a route and showing the result on the map, the following example shows how to extend RouteLayer to modify the ribbon, POI markers, and binding a popup to the markers.

 

The following JavaScript code creates a map, calculates a route, and adds the result to the map, while also customizing the ribbon and POI markers as well as binding a popup to the markers:

var map,
  dir;

map = L.map('map', {
  layers: MQ.mapLayer(),
  center: [ 40.045049, -105.961737 ],
  zoom: 9
});

dir = MQ.routing.directions();

dir.route({
  locations: [
    '80217',
    'Fraser, CO',
    'steamboat springs co'
  ],
  options: { avoids: ['toll road'] }
});

CustomRouteLayer = MQ.Routing.RouteLayer.extend({
  createStopMarker: function(location, stopNumber) {
    var custom_icon,
      marker;

    custom_icon = L.icon({
      iconUrl: 'https://www.mapquestapi.com/staticmap/geticon?uri=poi-red_1.png',
      iconSize: [20, 29],
      iconAnchor: [10, 29],
      popupAnchor: [0, -29]
    });

    marker = L.marker(location.latLng, { icon: custom_icon })
      .bindPopup(location.adminArea5 + ' ' + location.adminArea3)
      .openPopup()
      .addTo(map);

    return marker;
  }
});

map.addLayer(new CustomRouteLayer({
  directions: dir,
  fitBounds: true,
  draggable: false,
  ribbonOptions: {
    draggable: false,
    ribbonDisplay: { color: '#CC0000', opacity: 0.3 },
    widths: [ 15, 15, 15, 15, 14, 13, 12, 12, 12, 11, 11, 11, 11, 12, 13, 14, 15 ]
  }
}));

In the body of the page, create the 'map' element, which is where the map will appear:

<div id="map"></div>

Try It Now Try It On JSFiddle

Alternate Routes

The following example shows how to calculate a route while displaying alternate routes.

 

The following JavaScript code creates a map, calculates a route with alternates, and adds the route and (styled) alternates to the map:

var map,
  routeLayer,
  dir;

map = L.map('map', {
  layers: MQ.mapLayer(),
  center: [40.732672, -74.271125],
  zoom: 11,
  attributionControl: true
});

dir = MQ.routing.directions();

routeLayer = MQ.routing.routeLayer({
  directions: dir,
  fitBounds: true,
  ribbonOptions: {
    draggable: false,
    ribbonDisplay: { color: '#5882FA', opacity: 0.7 },
    widths: [ 10, 15, 10, 15, 10, 13, 10, 12, 10, 11, 10, 11, 10, 12, 10, 14, 10 ]
  },

  altRibbonOptions: {
    show: true,
    ribbonDisplay: { color: '#F78181', opacity: 0.7},
    hoverDisplay: { color: 'red', opacity: 0.6 }
  }
});

dir.route({
  maxRoutes: 5,
  timeOverage: 25,
  locations: [
    'wood-ridge, nj',
    'staten island, ny'
  ]
});

map.addLayer(routeLayer);

In the body of the page, create the 'map' element, which is where the map will appear:

<div id="map"></div>

Try It Now Try It On JSFiddle