Getting a route from Leaflet Routing Control based on a set of waypoints
HTML
<script src="http://cdn.leafletjs.com/leaflet-0.7.5/leaflet.js"></script>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.5/leaflet.css">
<script src="https://rawgit.com/perliedman/leaflet-routing-machine/master/dist/leaflet-routing-machine.min.js"></script>
<link rel="stylesheet" href="https://rawgit.com/perliedman/leaflet-routing-machine/master/dist/leaflet-routing-machine.css">
<script src="https://rawgit.com/perliedman/leaflet-routing-machine/master/examples/Control.Geocoder.js"></script>
<div id="map"></div>
CSS
html,
body,
#map {
height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
background: white;
}
.leaflet-routing-container {
display:none;
}
JavaScript
/////////////////////////////////////////////////////////////////////////////////////////////
//setting up the map//
/////////////////////////////////////////////////////////////////////////////////////////////
// set center coordinates
var centerlat = 34.05;
var centerlon = -118.25;
// set default zoom level
var zoomLevel = 11;
// initialize map
var map = L.map('map').setView([centerlat,centerlon], zoomLevel);
// set source for map tiles
ATTR = '© <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
'<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a> | ' +
'© <a href="http://cartodb.com/attributions">CartoDB</a>';
CDB_URL = 'http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png';
// add tiles to map
L.tileLayer(CDB_URL, {attribution: ATTR}).addTo(map);
/////////////////////////////////////////////////////////////////////////////////////////////
//adding data//
/////////////////////////////////////////////////////////////////////////////////////////////
var group = L.featureGroup();
var latlngArray = [];
var input = getPoints();
//populate array of lat lng points with input, and add individual points to map
for (var i = 0; i < input.length; ++i) {
var ltln = L.latLng(input[i][1], input[i][0]);
L.circleMarker(ltln, {
radius: 2
}).addTo(group);
latlngArray.push(ltln);
}
//create a routing control with waypoints from latlngArray, then hide the control
//the createMarker function overrides the routing machine's default waypoint behavior
//(here it returns nothing, which just keeps waypoint markers from being displayed)
var control = L.Routing.control({
waypoints: latlngArray,
show: false,
waypointMode: 'snap',
createMarker: function() {}
}).addTo(map);
//when the router finds a route, extract the coordinates into a new polyline
control.on('routeselected', function(e) {
L.polyline(e.route.coordinates, {
color: '#f00',
weight: 3
}).addTo(group);
...