AngularJS无法加载Bing地图

时间:2018-08-17 02:58:12

标签: javascript bing-maps

我正在使用AngularJS来显示Bing Maps,但错误显示为“ TypeError:无法读取null的属性'prototype'。”请在下面看看。

在我的Razor视图文件中具有以下内容:

<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>

我的JavaScript文件中有:

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
    });
}

更新

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();
   });
});

1 个答案:

答案 0 :(得分:1)

显然,由于初始化地图后,Bing Maps库尚未准备就绪,因此会发生此错误。

没有错误发生,showMap函数在经过一段时间的延迟(假设当时Bing Maps库已加载)后被调用,例如:

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

但是我会提出以下解决方案:

注册必应地图库准备就绪后需要触发的功能,如下所示:

Microsoft.Maps.CallbackOnLoad = "initMap";

并声明initMap一个 global 函数:

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

演示

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>