It's important to proceed with caution when using the following code:
$scope.on('$destroy', function(){
mapInstance = null;
})
In my experience, I encountered issues with memory usage due to old map instances lingering in the heap. This was particularly noticeable when navigating between pages and creating new map instances without properly removing the old ones from memory.
The recommended approach, as suggested in the linked answer, is to re-use your map instance instead of constantly removing and recreating it. To implement this, I created a solution where I passed the directive element to a service and dynamically created or appended the map within that element. Here is an example of how this can be implemented:
ng-view Element
<map-container></map-container>
Directive
angular.module('project')
.directive('mapContainer', function($timeout, mapService) {
return {
template: '<div></div>',
restrict: 'E',
replace: true,
link: function(scope, element) {
$timeout(function () {
mapService.createMap(element).then(function() {
//map creation complete
});
});
}
};
})
Service
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) {
element.append(map.getDiv());
resolve();
} else {
element.append('<div id="map_canvas"></div>');
mapOptions = {
zoom: zoom,
center: new google.maps.LatLng(lat, lng),
styles: hybridMap,
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);
resolve();
}
});
}
return {
createMap: function(elem) {
return initialiseGmap(elem);
},
getMap: function() {
return map;
},
getZoom: function() {
return zoom;
},
setZoom: function(value) {
map.setZoom(zoom);
}
// Additional functions for interacting with the map object can be added here as needed
};
});