How to include leaflet-routing-machine into angular 2 typescript webpack application How to include leaflet-routing-machine into angular 2 typescript webpack application typescript typescript

How to include leaflet-routing-machine into angular 2 typescript webpack application


I haven't worked with either Angular 2, nor TypeScript, but I suspect that TypeScript doesn't like that LRM attaches itself to the L object/namespace.

Note that LRM also exports itself as a normal CommonJS module, so you can do something like this instead of using L.Routing.Control:

var L = require('leaflet');var Routing = require('leaflet-routing-machine');var map = L.map(...);var routingControl = Routing.control({ ... });


This has been something that I struggled with for a while but finally got it working.This is how you import it:

import * as L from 'leaflet';import 'leaflet-routing-machine';

And in your systemjs.config

   map: {    'leaflet': 'npm:leaflet/dist/leaflet.js',}     packages: {           leaflet: {              defaultExtension: 'js'              }            }

To set up the routing in the component, make sure you are adding the routing to the map instead of the tile layer.

    ngAfterViewInit() {     var map = new L.Map("map")    let openmap = L.tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {        attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> ',       }).addTo(map);    let route = L.Routing.control({        waypoints: [          L.latLng(40.5663651,-75.6032277),          L.latLng(40.00195, -76.073299),          L.latLng(42.3673945,-83.0750408)        ]      }).addTo(map);}

I got a lot of the information for this on this question:How to import a module that extends another on the same namespace