Search code examples
angularjsleafletangular-leaflet-directive

AngularJS and Leaflet map centering bound to ng-repeat iteration variable


I am trying to bind the center attribute of a leaflet to the model like so:

<!DOCTYPE html>
<html>
<title>Test Leaflet</title>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.1/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet-0.7.1/leaflet.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<script src="angular-leaflet-directive.min.js"></script>
<script src="map.js"></script>
<body ng-app="mapApp" ng-controller="mapCtrl">
<ul>
<li ng-repeat="m in maps | orderBy:'ident':false">
        <div>
        {{m.ident}}
        <leaflet center="{{m.center}}" width="300px" height="300px"></leaflet>
        </div>
</li>
</ul>
</body>
</html>

with the JavaScript:

var mapApp = angular.module('mapApp', ['leaflet-directive']);
mapApp.controller('mapCtrl', ['$scope', function($scope, $http)
{
    $scope.maps = [
        { ident: "MAP1", center: { lat: 45, lng: 90, zoom: 10 } },
        { ident: "MAP2", center: { lat: -45, lng: -90, zoom: 10 } },
        { ident: "MAP3", center: { lat: 45, lng: -90, zoom: 10 } },
        { ident: "MAP4", center: { lat: -45, lng: 90, zoom: 10 } }
      ];
}]);

however this does not work. Only once I remove the center attribute do I get the maps but then they're not centered i.e.:

<leaflet width="300px" height="300px"></leaflet>

Can anyone assist in getting this working without changing the overall structure entirely.

(Apology in advance: I could not get the example to work on either Plunker or Fiddle even though it works fine in all my browsers)


Solution

  • So I decided to mock it up and test a few things. This works for me...

    HTML:

    <ul>
    <li ng-repeat="m in maps | orderBy:'ident':false">
            <div>
            {{m.ident}}
            <leaflet id="{{m.ident}}" center="m.center" width="300px" height="300px"></leaflet>
            </div>
    </li>
    </ul>
    

    JS:

    $scope.center = {center: { lat: 45, lng: 90, zoom: 1 }};
    
    $scope.maps = [
        { ident: "MAP1", center: { lat: -45, lng: -90, zoom: 18 } },
        { ident: "MAP2", center: { lat: -45, lng: -90, zoom: 14} },
        { ident: "MAP3", center: { lat: -45, lng: -90, zoom: 10} },
        { ident: "MAP4", center: { lat: -45, lng: -90, zoom: 6 } }
      ];
    

    Let me know...