[英]AngularJS fails to load Bing Maps
我正在使用 AngularJS 來顯示 Bing 地圖,但錯誤顯示“TypeError:無法讀取 null 的屬性‘原型’”。 請看下面。
在我的 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();
});
});
顯然,發生此錯誤是因為初始化地圖后 Bing 地圖庫尚未准備好。
沒有發生錯誤,是在延遲一段時間后調用了showMap
函數(假設此時已加載 Bing Maps 庫),例如像這樣:
$timeout(function() { $scope.initMap()}, 2000);
但我會提出以下解決方案:
注冊必應地圖庫准備好后需要觸發的函數,如下所示:
Microsoft.Maps.CallbackOnLoad = "initMap";
並聲明initMap
一個全局函數:
$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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.