Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 865
qopuir Avatar asked Feb 18 '13 15:02

qopuir


2 Answers

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

like image 164
Andrew Joslin Avatar answered Oct 03 '22 02:10

Andrew Joslin


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);
});
like image 45
qopuir Avatar answered Oct 03 '22 02:10

qopuir