假设我有一个单页应用程序(Angular JS 应用程序),我在元素 id googleMap
上绘制了一个 Google Map 实例 -
var mapInstance = new google.maps.Map(document.getElementById(`googleMap`), mapOption)
然后我在应用程序路由中导航,由于这个原因,破坏了 googleMap
DOM 元素,最后我回到了这个元素的路线,现在我必须在这个元素上重新绘制 map .
重新绘制 map 的正确方法是什么?
正如我在 this answer 中读到的那样我不必重新创建它,而是使用相同的实例。
最佳答案
我会小心的
$scope.on('$destroy', function(){
mapInstance = null;
})
我有一个包含我的 map DOM 元素的指令,并调用此方法从数据层和所有监听器中删除所有 map 引用,然后将 map 设置为空。我正在检查页面导航之间的堆, map 实例正在重新创建,但旧 map 仍在堆中,导致内存使用量不断增加。
此外,您链接的答案建议重新使用您的 map 实例,而不是尝试将其删除。谷歌地图开发者也推荐这种方法。我找到的解决方案是将您的指令元素传递给服务,并将子元素附加到在新子元素上创建 map 的那个元素。如果 map 已经存在,只需将 map 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);
}
};
});
关于javascript - 在单页应用程序上重用 Google Maps API 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36282395/