Kermani Kermani - 4 months ago 90
AngularJS Question

How to remove drawn polygon on Google map

I have a map, using ng-map directive, I also have a

which allows me to draw shapes on the map.

I just want to allow my user to draw one polygon on map, here is my HTML:

<div ng-controller="CreateOrderController as vm" map-lazy-load="https://maps.google.com/maps/api/js"
map-lazy-load-params="{{googleMapsUrl}}">
<ng-map zoom="4" center="33.134394, 53.664248"
map-type-id="ROADMAP">
<drawing-manager
on-overlaycomplete="vm.onMapOverlayCompleted()"
drawing-control-options="{position: 'TOP_CENTER',drawingModes:['polygon']}"
drawingControl="true"
drawingMode="null">
</drawing-manager>
</ng-map>
</div>


This is my controller:

var vm = this;


$scope.googleMapsUrl="https://maps.googleapis.com/maps/api/js?key=myKeyIsHere&sensor=false&libraries=drawing";
NgMap.getMap().then(function(map) {
vm.map = map;
});


vm.onMapOverlayCompleted = function(e){
var shapePath=e.overlay.getPath().getArray(); //This returns an array of drawn polygon cordinates

//Just for example, here I want to delete the drawn polygon:
$scope.deletePolygon();
};


$scope.deletePolygon = function() {
//According to Google's docs: https://developers.google.com/maps/documentation/javascript/examples/polyline-remove
vm.map.setMap(null);
};


The
deletePolygon
function returns an error:


Uncaught TypeError: vm.map.setMap is not a function


I know that map object does not contain
setMap
function, but Google docs says I can remove a polygon shape using
setMap(null)


Any idea about how to remove/delete the polygon shape?

Answer

The callback function of the overlaycomplete event is passed a parameter of type google.maps.drawing.OverlayCompleteEvent, which according to the docs has overlay parameter, referencing to the newly created object. You need to call .setMap(null) on that object. So your code should look something like this:

vm.onMapOverlayCompleted = function(e){
    var shapePath= e.overlay.getPath().getArray();  //This returns an array of drawn polygon cordinates

    e.overlay.setMap(null); //this will delete any created shape (polygon, polyline, etc) right after it is created. If you want to instead delete it later, just store the reference to overlay and call setMap(null) on it later.
};