I would be careful with
$scope.on('$destroy', function(){
mapInstance = null;
})
I had a directive containing my map DOM element, and was calling this method to remove all map references from the datalayer, all listeners, and then setting the map to null. I was checking the heap between page navigation and the map instance was being created anew, but the old map(s) were still in the heap leading to ever increasing memory usage.
Also the answer you linked recommends re-using your map instance instead of trying to remove it. The google maps developers also recommend this approach. The solution I found was to pass your directive element to a service, and append a child element to that creating the map on the new child element. If the map already exists, just append the map div to the directive element. Here is my code below.
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 () {
//Use the $timeout to ensure the DOM has finished rendering
mapService.createMap(element).then(function() {
//map now exists, do whatever you want with it
});
});
}
};
})
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) {
//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);
}
};
});