使用Angular v1的Bing Maps v8

时间:2016-10-12 14:14:18

标签: angularjs bing-maps

我试图将我的Bing Maps v7升级到v8,根据文档我应该可以交换网址,它可以解决可能的小问题。

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src='https://www.bing.com/api/maps/mapcontrol?branch=release'></script>
<body ng-app="myApp">

<div ng-controller="bingCtrl" ng-init="init()" ng-cloak>
    <div id="mapDiv"></div>
</div>

<script>
var app = angular.module("myApp", []);
app.controller("bingCtrl", function($scope) {
    $scope.map = null;
    $scope.init = function() {
          $scope.map = new Microsoft.Maps.Map(document.getElementById('mapDiv'));
    };
});
</script>

</body>
</html>

我删除了所有代码以查看是否可以隔离问题,我可以使用上面的代码。我收到以下错误。任何想法为什么这不起作用?

  

TypeError:无法读取属性&#39;原型&#39;为null

2 个答案:

答案 0 :(得分:2)

当地图通过ng-init初始化时,似乎Bing Maps API尚未就绪。为了保证加载Bing地图库,您可以使用ready事件。

<强>解决方案

ng-init="init()"替换为:

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

演示:plunker

答案 1 :(得分:0)

换出网址仅适用于某些应用,而非所有应用。这不是标准应用。

在这看来,看起来你的Angular代码在Bing Maps代码完全加载之前就已经开始了。因此,尚未定义map API的某些部分,并且遇到空引用。说实话,当您使用v7时,此代码可能无法100%工作。它可能是第一次失败,然后一旦地图控件被缓存,就工作了。

有几个人使用Bing Maps V8和Angular 2,这是我使用Angular 1时遇到的第一个应用程序。这是你应用程序的修改版本,但它有点挫败了使用Angular的目的。

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src='https://www.bing.com/api/maps/mapcontrol?branch=release'></script>
<body ng-app="myApp">

<div ng-controller="bingCtrl" ng-init="init()" ng-cloak>
    <div id="mapDiv"></div>
</div>

<script>
var app = angular.module("myApp", []);
app.controller("bingCtrl", function($scope) {
    $scope.map = null;
    $scope.init = function() {     
        //Try loading the map every 100ms until it works.
        var interval = setInterval(function(){
            try{
                $scope.map = new Microsoft.Maps.Map(document.getElementById('mapDiv'));
                clearInterval(interval);
             }catch(e){
             }
         }, 100);
    };  
});
</script>

</body>
</html>

以下是开发人员使用Bing Maps V8和Angular 2的一些帖子:

How to add Bing Maps v8 to Angular 2.0?

https://github.com/youjustgo/ng2-bingmaps

我确定有更好的方法可以做到这一点。开发团队也会对此进行研究。