angularleafletbing-maps

Angular 6 - Add Bing Maps to Leaflet Maps


I am using leaflet-bing-layer plugin, in order to add a Bing based map with Leaflet.
Since I am using also OSM, I import both leaflet and leaflet-bing-layer. The import statements are as follows:

import * as L from 'leaflet';
import * as B from 'leaflet-bing-layer';

And the usage of leaflet inside the component LeafletMapComponent:

constructor () {
    this.baseMaps = {
      OpenStreetMap: L.tileLayer ("https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png", {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>, Tiles courtesy of <a href="https://hot.openstreetmap.org/" target="_blank">Humanitarian OpenStreetMap Team</a>'
      }),
      BingMap: B.tileLayer.bing(LeafletMapComponent.BING_KEY, {type: 'AerialWithLabels'})
    };
  }

Unfortunately, The ling BingMap: B.tileLayer.bing(... gets an error: Cannot read property 'bing' of undefined

I didn't find any working example of Bing maps in Angular and Typescript, so I guess that there is something missing here.

Any thoughts of what am I doing wrong?


Solution

  • You should import leaflet-bing-layer as following:

    import * as L from 'leaflet';
    import 'leaflet-bing-layer';
    

    Then, you can add your Bing tile layer as following.

    L.tileLayer.bing(LeafletMapComponent.BING_KEY).addTo(map);
    

    This will throw you a type error that

    property 'bing' does not exist on type 'tileLayer' 
    

    but you can overcome this error by defining L as custom type:

    (L as any).tileLayer.bing(LeafletMapComponent.BING_KEY).addTo(map);
    

    Note: I would not create the map on the constructor function. I would choose a lifecycle hook method instead, so that I can be sure that map is created after view is loaded.