qopuir
qopuir

Reputation: 369

AngularUI - Google Maps - Remove marker

I am using AngularUI Google Maps directive in this way:

UpdateData.html

<div ng-repeat="marker in myMarkers" ui-map-marker="myMarkers[$index]"></div>

<div class="control-group">
    <label class="control-label">Situación</label>
    <div class="controls">
        <div id="map_canvas" ui-map="model.myMap" class="map" ui-event="{'map-click': 'addMarker($event)'}" ui-options="mapOptions"></div>
    </div>
</div>

UpdateController

if (!$scope.myMarkers) {
    $scope.myMarkers = [];
}

if (!$scope.myMap) {
    $scope.model = {
        myMap: undefined
    };
}

$scope.mapOptions = {
    center : new google.maps.LatLng(35.784, -78.670),
    zoom : 15,
    mapTypeId : google.maps.MapTypeId.ROADMAP
};

$scope.addMarker = function($event) {
    $scope.myMarkers.push(new google.maps.Marker({
        map : $scope.model.myMap,
        position : $event.latLng
    }));

    $scope.event.lat = $event.latLng.lat();
    $scope.event.lng = $event.latLng.lng();
};

I can add new markers and the map is updated successfully by I can't remove them. What I do is the following:

$scope.myMarkers.splice(0, $scope.myMarkers.length);

myMarkers array gets empty but the map still contains removed markers. It seems that myMarkers array and map are synchronized when pushing new markers to myMarkers array but not when myMarkers array is cleared.

Upvotes: 5

Views: 7186

Answers (2)

qopuir
qopuir

Reputation: 369

I answer to myself. Before executing this line

$scope.myMarkers.splice(0, $scope.myMarkers.length);

This should be done:

angular.forEach($scope.myMarkers, function(marker) {
    marker.setMap(null);
});

Upvotes: 7

Andrew Joslin
Andrew Joslin

Reputation: 43023

Try myMarker.setMap(null).

You still have to use the Google Maps API to do everything, there's not much magic involved. The only reason ui-map-marker is a directive is so you can easily hook up DOM events to your markers

Upvotes: 8

Related Questions