我会小心的
$scope.on('$destroy', function(){
mapInstance = null;
})
我有一个包含我的地图 DOM 元素的指令,并且正在调用此方法以从数据层、所有侦听器中删除所有地图引用,然后将地图设置为 null。我正在检查页面导航之间的堆,并且正在重新创建地图实例,但旧地图仍在堆中,导致内存使用量不断增加。
您链接的答案还建议重新使用您的地图实例,而不是尝试删除它。谷歌地图开发人员也推荐这种方法。我找到的解决方案是将您的指令元素传递给服务,并将子元素附加到在新子元素上创建地图的那个。如果地图已经存在,只需将地图 div 附加到指令元素。下面是我的代码。
ng-view 元素
<map-container></map-container>
指令
angular.module('project')
.directive('mapContainer', function($timeout, mapService) {
return {
template: '<div></div>',
restrict: 'E',
replace: true,
link: function(scope, element) {
$timeout(function () {
//Use the $timeout to ensure the DOM has finished rendering
mapService.createMap(element).then(function() {
//map now exists, do whatever you want with it
});
});
}
};
})
服务
angular.module('project')
.service('mapService', function($q) {
var lat = -33.1798;
var lng = 146.2625;
var minZoom = 5;
var maxZoom = 20;
var zoom = 6;
var mapOptions = null;
var map = null;
function initialiseGmap(element) {
return $q(function (resolve) {
if (map) {
//Map already exists, append it
element.append(map.getDiv());
resolve();
} else {
//No map yet, create one
element.append('<div id="map_canvas"></div>');
mapOptions = {
zoom: zoom,
center: new google.maps.LatLng(lat, lng),
styles: hybridMap, //your style here
minZoom: minZoom,
maxZoom: maxZoom,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
streetViewControl: false,
panControl: false,
scaleControl: true,
zoomControl: false
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
//create any map listeners you want here. If you want to add data to the map and add listeners to those, I suggest a seperate service.
resolve();
}
});
}
return {
createMap: function(elem) {
return initialiseGmap(elem);
},
getMap: function() {
return map;
},
//Create as many functions as you like to interact with the map object
//depending on our project we have had ones to interact with street view, trigger resize events etc etc.
getZoom: function() {
return zoom;
},
setZoom: function(value) {
map.setZoom(zoom);
}
};
});