Reputation: 14398
I have an Angular service function to build a mapbox map like so:
app.service("MapService", [function(){
//mapbox vars
var map = {
minZoom: 11,
id: "xxxxxxxx",
token: "xxxxxxxx"
};
//build map
this.buildMap = function(lat, lon, zoom){
//map bounds
var southWest = L.latLng(54.04407014753034, -0.745697021484375),
northEast = L.latLng(53.45698455620496, -2.355194091796875),
bounds = L.latLngBounds(southWest, northEast);
//build map object
L.mapbox.accessToken = map.token;
map.obj = L.mapbox.map("map", map.id, {
maxBounds: bounds,
zoomControl: false,
minZoom: map.minZoom,
attributionControl: false
}).setView([lat, lon], zoom, {
pan: { animate: true },
zoom: { animate: true }
});
}
}]);
This simply populates a div:
<div id="map"></div>
When I go to a new Angular view and call this function again (to populate a new div
with id map
with the map) it gives me the error:
Map container is already initialized
How do I solve this problem?
Upvotes: 0
Views: 2227
Reputation: 28638
Using a directive is much more suitable for this kind of purpose, you won't run into stuff like this. In the following directive i'm using Leaflet, but it's just the same as using Mapbox (Mapbox is an extended version of Leaflet):
angular.module('app').directive('leaflet', [
function () {
return {
restrict: 'EA',
replace: true,
template: '<div></div>',
link: function (scope, element, attributes) {
scope.$emit('leaflet-ready', new L.Map(element[0]));
}
};
}
]);
Use it in your view:
<leaflet></leaflet>
Controller:
angular.module('app').controller('map1Controller', function($scope) {
$scope.$on('leaflet-ready', function (e, leaflet) {
// leaflet var contains map instance, do stuff
})
});
Here's an example of the concept: http://plnkr.co/edit/SFgGhVUtBOqsIwYuwNuv?p=preview
Upvotes: 0
Reputation: 1634
You have to destroy the map before reinitializing it. Use the following
if(map.obj != undefined) map.obj.remove();
before
map.obj = L.mapbox.map("map", map.id, {
Upvotes: 1