How to add Bing Maps v8 to Angular 2.0?

前端 未结 3 1790
情深已故
情深已故 2020-12-09 11:35

I want to add Bing Map V8 control to my Anguar 2.0 project. I want to know what I need to do to add Bing Map V8 into Angular 2.0 project. I have attached my implementation.

相关标签:
3条回答
  • 2020-12-09 12:01

    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',
        });
    }
    
    0 讨论(0)
  • 2020-12-09 12:06

    There is a community effort to build Angular2 directives for Bing Maps. Still in alpha version, but a basic demo can be found here: http://ng2-bingmaps.azurewebsites.net/

    The Github repo is here: https://github.com/youjustgo/ng2-bingmaps

    0 讨论(0)
  • 2020-12-09 12:10

    Your code is almost ok, you just need few modifications

    1- in index.html remove the callback function and the div

    <div id='myMap' style='width: 100vw; height: 100vh;'></div>
    <script type='text/javascript'>
        function loadMapScenario() {
            var map = new Microsoft.Maps.Map(document.getElementById('myMap'), {
                    credentials: 'My Bing Map Key - I removed here'
            });
            var pushpin = new Microsoft.Maps.Pushpin(map.getCenter(), null);
            var layer = new Microsoft.Maps.Layer();
            layer.add(pushpin);
            map.layers.insert(layer);
        }
    </script>
    

    Also, in index.html, remove the callback parameter from the script import.

    <script type='text/javascript' src='http://www.bing.com/api/maps/mapcontrol?branch=experimental&callback=loadMapScenario' async defer></script>

    To be:

    <script type='text/javascript' src='http://www.bing.com/api/maps/mapcontrol?branch=experimental' async defer></script>

    Now, you have the script loaded, all you need to do is create the map in your component

    @Component({
        selector: 'pm-map',
        template: `
        <div class='panel panel-primary'>
          <div class='panel-heading'>
              {{pageTitle}}
          </div>
          <div #myMap style='width: 100%; height: 500px;'></div> 
        </div>`
    })
    export class MapComponent implements OnInit {
      @ViewChild('myMap') myMap; // using ViewChild to reference the div instead of setting an id
      public pageTitle: string = "Map";
    
      ngAfterViewInit(){  // after the view completes initializaion, create the map
        var map = new Microsoft.Maps.Map(this.myMap.nativeElement, {
            credentials: 'Bing Map Key - I removed it here'
        });
        var pushpin = new Microsoft.Maps.Pushpin(map.getCenter(), null);
        var layer = new Microsoft.Maps.Layer();
        layer.add(pushpin);
        map.layers.insert(layer);
      }
    }
    

    check it in this plunk

    0 讨论(0)
提交回复
热议问题