Search code examples
angularjsleafletmarkersangular-leaflet-directive

Markers not appearing in leaflet


I am trying to load the position form the database and assign it to marker(lat, lng). But when I push the new marker to my markers array, the markers are not appearing on the leaflet map.

I am creating the marker like this.

$scope.markers = new Array();

$scope.alerts = Alert.query(function (){
        $scope.markers.push({
            lat: $scope.alerts[0].g_pos.coordinates[0],
            lng: $scope.alerts[0].g_pos.coordinates[1],
            message: "Added marker from query"
        });
        console.log($scope.markers[0].lat);
        console.log($scope.markers[0].lng);
    });

I am able to see the marker.lat and marker.lng with correct values in the console. Its just not appearing in the leaflet map.

I also tried using a watchCollection() but no luck.

$scope.$watch('markers', function(newMarkers, oldMarkers) {
        if (newMarkers.length > 0) {
            console.log(newMarkers[0].lat);
            console.log(newMarkers[0].lng);
        }           
    }, true);

Solution

  • Try to wrap your code with $timeout. In this way, AngularJS will know about your changes.

    $scope.markers = new Array();
    
    $scope.alerts = Alert.query(function (){
        $timeout(function() {
            $scope.markers.push({
                lat: $scope.alerts[0].g_pos.coordinates[0],
                lng: $scope.alerts[0].g_pos.coordinates[1],
                message: "Added marker from query"
            });
            console.log($scope.markers[0].lat);
            console.log($scope.markers[0].lng);
        });
    });
    

    Note: You should inject the $timeout service into your controller.

    Here is a SO thread regarding this issue.

    Also here is an article, where the author talks about the $apply() method, which is another solution for this.