Search code examples
angulartypescriptleafletangular7

Nominatim is undefined when I use leaflet-routing-machine with angular 7


Hello !

I use Leafletjs library with Angular 7 (typeScript) for the first time, for leaflet routing machine, I use this block of code, I have this error have you any idea ? :

component.ts :

L.Routing.control({
      waypoints: [L.latLng(48.8534, 2.3488), L.latLng(44.837789, -0.57918),],
      routeWhileDragging: true,
      show: true,
      language: 'fr',
      geocoder: L.Control.Geocoder.nominatim(),
      autoRoute: true
    }).addTo(this.mapInstance);

Solution

  • You get this error because you either have not imported the library or you have imported it but it loads after the map initialization.

    Import like this:

    import "leaflet-routing-machine/dist/leaflet-routing-machine.css";
    import "leaflet-routing-machine";
    

    and then when the component has loaded:

    ngOnInit() {    
        this.map = L.map("map").setView([51.505, -0.09], 13);
    
        L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
          attribution:
            '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        }).addTo(this.map);
    
        L.Routing.control({
          waypoints: [L.latLng(57.74, 11.94), L.latLng(57.6792, 11.949)],
          routeWhileDragging: true
        }).addTo(this.map);
      }
    

    Demo

    Note that because of an API limitation you should test it in a incognito browser mode sometimes to get the route.