Search code examples
javascriptangularjsangular-leaflet-directive

AngularJS - Leaflet - The "center" property is not defined in the main scope


I've set up leaflet.js correctly, and the map renders as expected in my app. However, I keep getting the following error message: The "center" property is not defined in the main scope. What am I doing wrong?

In my view:

<leaflet markers="markers" center="osloCenter"></leaflet>

In my controller:

function MapCtrl($scope) {
    angular.extend($scope, {
          osloCenter: {
                lat: 59.91,
                lng: 10.75,
                zoom: 12
        },
        markers: {
            osloMarker: {
                lat: 59.91,
                lng: 10.75,
                focus: true,
                draggable: false
            }
        defaults: {
            scrollWheelZoom: false
        }
    });
};

I've also tried the following:

       scope.osloCenter  = {
            lat : 59.91,
            lng : 10.75,
            zoom : 12
        };

        $scope.osloMarker = {
            lat: 59.91,
            lng: 10.75,
            focus: true,
            draggable: false
        };

Solution

  • The object needs to be initialised at app level (i.e app.js) at $rootScope:

     function runBlock($rootScope) {
       angular.extend($rootScope, {
         center: {},
         markers: {},
       });
     }
    

    then the required values can be set within the controller:

    var centerLat = parseFloat($stateParams.lat);
    var centerLng = parseFloat($stateParams.lon);
    
    $scope.center = {
      lat: centerLat,
      lng: centerLng,
      zoom: 15
    };    
    
    $scope.markers = {
      marker: {
        lat: centerLat,
        lng: centerLng,
        focus: true,
        draggable: false
      }
    };