The Traffic Plugin for Leaflet makes it easy to display traffic information on a map using the MapQuest Traffic API Web Service. 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 Traffic Plugin, you will need to include the Maps Plugin as well as the Leaflet library and associated CSS files.
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 YOUR_KEY_HERE 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-traffic.js?key=KEY"></script>
The following example shows how to easily add the traffic overlay and traffic incidents to the map.
The following JavaScript code creates a map and adds the traffic layer to it:
window.onload = function() {
var map = L.map('map', {
layers: MQ.mapLayer(),
center: [ 40.731701, -73.993411 ],
zoom: 12
});
MQ.trafficLayer().addTo(map);
};
In the body of the page, create the 'map' element, which is where the map will appear:
<div id="map"></div>
The following example shows how to use the layers control within Leaflet to toggle between the traffic flow and traffic incidents layers.
The following JavaScript code creates a map and adds a layers control that allows the user to toggle between the map types, traffic flow, and traffic incident layers.
var mapLayer = MQ.mapLayer(),
map;
map = L.map('map', {
layers: mapLayer,
center: [ 40.731701, -73.993411 ],
zoom: 12
});
L.control.layers({
'Map': mapLayer,
'Satellite': MQ.satelliteLayer(),
'Dark': MQ.darkLayer(),
'Light': MQ.lightLayer()
}, {
'Traffic Flow': MQ.trafficLayer({layers: ['flow']}),
'Traffic Incidents': MQ.trafficLayer({layers: ['incidents']})
}).addTo(map);
In the body of the page, create the 'map' element, which is where the map will appear.
<div id="map"></div>