I initially tried the accepted answer and ran into the issue some people had in the comments where upon load 'prototype' was null.
I initially solved this by using a try/catch with a setTimeout in the catch that would attempt to load bing after a second. This worked but was a very sloppy solution.
Eventually I looked for how people loaded Google Maps in angular to see if there was a better solution. Thankfully there is and it uses promises.
The solution that worked for me was found here in this answer. Full credit for this goes to them.
First create a service to load your map...
map-loader-service.service
import { Injectable } from '@angular/core';
const url = 'http://www.bing.com/api/maps/mapcontrol?callback=__onBingLoaded&branch=release';
@Injectable()
export class BingMapsLoader {
private static promise;
public static load() {
// First time 'load' is called?
if (!BingMapsLoader.promise) {
// Make promise to load
BingMapsLoader.promise = new Promise( resolve => {
// Set callback for when bing maps is loaded.
window['__onBingLoaded'] = (ev) => {
resolve('Bing Maps API loaded');
};
const node = document.createElement('script');
node.src = url;
node.type = 'text/javascript';
node.async = true;
node.defer = true;
document.getElementsByTagName('head')[0].appendChild(node);
});
}
// Always return promise. When 'load' is called many times, the promise is already resolved.
return BingMapsLoader.promise;
}
}
In the parent component to the component that contains the bing map element have this code...
import { BingMapsLoader } from './services/map-loader-service/map-loader-service.service';
export class BingMapParentComponent {
mapReady = false;
constructor() {
BingMapsLoader.load()
.then(res => {
console.log('BingMapsLoader.load.then', res);
this.mapReady = true;
});
}
}
Additionally, in the template of parent component have this code which will prevent the bing maps component from being initialized until it is ready.
<app-bing-map *ngIf='mapReady'></app-bing-map>
Now, in the bing-map.component itself we want to wait until the component is in the DOM before loading the map.
ngOnInit() {
if (typeof Microsoft !== 'undefined') {
console.log('BingMapComponent.ngOnInit');
this.loadMap();
}
}
And finally, you load the bing map in the bing-map.component
loadMap() {
this.map = new Microsoft.Maps.Map(document.getElementById('mapId'), {
credentials: 'Your Bing Maps Key Here',
});
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…