Phil
Phil

Reputation: 349

AngularJS fails to load Bing Maps

I'm using AngularJS to display Bing Maps, but the error says "TypeError: Cannot read property 'prototype' of null". Please take a look below.

In my Razor view file has the following:

<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript" src="~/lib/angular/angular.min.js"></script>
<script src="~/js/Site.js"></script>
----
----
--
<div ng-app="myDisplayItems">
    <div ng-controller="myDisplayItemsController">
        <div id="myMap"></div>
    </div>
</div>

In my JavaScript file has:

var displayItems = angular.module("myDisplayItems", []);
displayItems.controller("myDisplayItemsController", function myDisplayItemsController($scope) {
    showMap();
});

function showMap() {         
    var key = "######";

    var map = new Microsoft.Maps.Map('#myMap', {
        credentials: key,
        zoom: 3
    });
}

Update:

var displayItems = angular.module("myDisplayItems", []);
displayItems.controller("myDisplayItemsController", function myDisplayItemsController($scope) {
   $scope.map = null;
   $scope.init = function () {
         $scope.map = showMap();
   };

   angular.element(document).ready(function () {
         $scope.init();
   });
});

Upvotes: 1

Views: 565

Answers (1)

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59358

Apparently this error occurs since Bing Maps library is not yet ready once the map is initialized.

No error occurs, is showMap function is invoked after some delay (assuming Bing Maps library has been loaded by that moment), for example like this:

$timeout(function() { $scope.initMap()}, 2000); 

But i would propose the following solution:

Register the function that needs to be triggered once Bing Maps library is ready, like this:

Microsoft.Maps.CallbackOnLoad = "initMap";

and declare initMap a global function:

$window.showMap = function () {
   //...
}

Demo

angular.module('mapApp', []);
    angular
        .module('mapApp')
        .controller('MapController', MapController);

    function MapController($scope, $window) {

        $window.initMap = function () {
            let map = new window.Microsoft.Maps.Map(
                document.getElementById('myMap'), {
                    credentials: 'AjwUEXFZA8SMyy8CaJj59vJKVDoWohNXVFz_uGyHlT8N40Jgr-zrhvcxbTNRyDqn'
                });
            map.setView({
                zoom: 6,
                center: new Microsoft.Maps.Location(52.406978607177734, -1.5077600479125977)
            });
        }

        Microsoft.Maps.CallbackOnLoad = "initMap";
    }
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

<div ng-app="mapApp" ng-controller="MapController">
    <div id="myMap" style="width:600px;height:400px;"></div>
</div>

Upvotes: 1

Related Questions