Search code examples
angularjsangularjs-directiveskmaps

Using Skobbler in AngularJS directive: 'Map container is already initialized.'


Using a directive to render the Skobbler leaflet:

angular.module('app.directives').directive('skm', function()
{
    return {
        restrict: 'E',
        replace: true,
        scope: false,
        template: '<div></div>',
        link: function(scope, element, attrs) {

            var map = L.skobbler.map('skm', scope.skm);

            // ....
        }
    }
});

This directive is used on different routes/partials in a similar way:

<skm id="skm"></skm>

Version info:

  • Skobbler 2.0
  • AngularJS 1.2.16

When moving from page 1 to page 2, no problem. However, going back to page 1:

    Error: Map container is already initialized.

I've tried storing the map object and using map.remove(), which removes the error but stops the map from rendering.

FIXED: See my answer below. (Use unique ID's in each partial and grab those)


Solution

  • Fixed: Simply put a unique ID in each partial and grab the ID in the directive, then create the leaflet with this ID.

    Partial 1:

    <skm id="skm1"></skm>
    

    Partial 2:

    <skm id="skm2"></skm>
    

    Directive:

    angular.module('app.directives').directive('skm', function()
    {
        return {
            restrict: 'E',
            replace: true,
            scope: false,
            template: '<div></div>',
            link: function(scope, element, attrs) {
    
                var map = L.skobbler.map(attrs.id, scope.skm);
    
                // ....
            }
        }
    });
    

    What didn't work:

    • replacing the outerHTML with original HTML on directive $destroy (directive didn't play well)
    • map.remove() (Skobbler didn't care)
    • Shouting profanities at the Skobbler library (Skobbler didn't care)