JSFiddle - React, Tailwind, and code Playground

Setting waypoints with a map click in Leaflet Routing Machine

by nathansnider

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>
<script src="https://rawgit.com/jacobtoye/Leaflet.iconlabel/master/dist/leaflet.iconlabel.js"></script>
<link rel="stylesheet" href="https://rawgit.com/jacobtoye/Leaflet.iconlabel/master/dist/leaflet.iconlabel.css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css">
<script src="//cdn.rawgit.com/CliffCloud/Leaflet.EasyButton/master/src/easy-button.js"></script>
<link rel="stylesheet" href="//cdn.rawgit.com/CliffCloud/Leaflet.EasyButton/master/src/easy-button.css">
<div id="map"></div>

CSS

html,
body,
#map {
  height: 100%;
  width: 100%;
  padding: 0px;
  margin: 0px;
  background: white;
}

JavaScript

var map = new L.Map('map').setView([34.07, -118.2], 11);

L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
  attribution: '� OpenStreetMap contributors'
}).addTo(map);

function button(label, container) {
  var btn = L.DomUtil.create('button', '', container);
  btn.setAttribute('type', 'button');
  btn.innerHTML = label;
  return btn;
}

var control = L.Routing.control({
  waypoints: [null],
  routeWhileDragging: true,
  show: true,
  geocoder: L.Control.Geocoder.nominatim(),
  autoRoute: true
}).addTo(map);

map.on('click', function(e) {
  var container = L.DomUtil.create('div'),
    startBtn = button('Start from this location', container),
    destBtn = button('Go to this location', container);

  L.DomEvent.on(startBtn, 'click', function() {
    control.spliceWaypoints(0, 1, e.latlng);
    map.closePopup();
  });

  L.DomEvent.on(destBtn, 'click', function() {
    control.spliceWaypoints(control.getWaypoints().length - 1, 1, e.latlng);
    map.closePopup();
  });

  L.popup()
    .setContent(container)
    .setLatLng(e.latlng)
    .openOn(map);
});