我有一个Angular服务函数来构建一个mapbox map,如下所示:
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 }
});
}
}]);
这只是填充div:
<div id="map"></div>
当我转到新的Angular视图并再次调用此函数时(使用地图填充ID为div
的新map
),它会给出错误:
Map container is already initialized
如何解决这个问题?
答案 0 :(得分:1)
您必须在重新初始化之前销毁地图。使用以下
if(map.obj != undefined) map.obj.remove();
之前
map.obj = L.mapbox.map("map", map.id, {
答案 1 :(得分:0)
使用指令更适合这种目的,你不会遇到像这样的东西。在下面的指令中,我使用的是Leaflet,但它与使用Mapbox相同(Mapbox是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]));
}
};
}
]);
在您的视图中使用它:
<leaflet></leaflet>
控制器:
angular.module('app').controller('map1Controller', function($scope) {
$scope.$on('leaflet-ready', function (e, leaflet) {
// leaflet var contains map instance, do stuff
})
});
以下是该概念的示例:http://plnkr.co/edit/SFgGhVUtBOqsIwYuwNuv?p=preview