I have 2 options in my google map.
-->one is polygon and another one is draw lines.
Now am trying to perform undo functionality in my page.When I click undo button recently added line should be removed(that may be in either polygon option or draw line option).
Is it possible?
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.MARKER,
drawingControl: true,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: ['polygon', 'polyline']
},
circleOptions: {
strokeColor: '#00DB00',
fillColor: 'green',
fillOpacity: 0.05,
strokeWeight: 5,
clickable: false,
editable: true,
zIndex: 1
}
});
drawingManager.setMap(map);
google.maps.event.addListener(drawingManager, 'overlaycomplete', function (event)
{
if (event.type === 'marker') console.log('Lat: ' + event.overlay.position.lat() + ', Long: ' + event.overlay.position.lng())
else displayPolyLatLng(event.overlay.getPath().b);
});
function displayPolyLatLng(pointArray)
{debugger
var result=" ";
for (var i = 0; i < pointArray.length; i++)
{
result +='<b>Lat: ' + pointArray[i].lat() + ', Long: ' + pointArray[i].lng()+ '</b><br/>';
}
$('#info').html(result);
/*var lastEl = pointArray[pointArray.length-1];
alert(lastEl)
if(lastEl.length>1){
undo_redo.push(lastEl.pop());
} */
}
}
function removeLine(){
polylines.remove(polylines.size() - 1)
}
fiddle: https://jsfiddle.net/rc5p32nt/
Basically what @geocodezip said...
Keep a reference to the shapes added:
var overlays = [];
You can then push the latest overlay object event.overlay in the overlaycomplete event:
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
overlays.push(event.overlay); // store reference to added overlay
});
Finally, on click of the Undo button hide the overlay via setMap(null):
// undo last overlay action
function removeLine() {
var lastOverlay = overlays.pop();
if (lastOverlay) lastOverlay.setMap(null);
}
Note that this doesn't remove the object, just hides it from showing on the map. If you want to remove the overlay completely you should then also set it to null.
You can show them again - if you wanted to add a Redo button (in this case you wouldn't pop them as I have done). See https://developers.google.com/maps/documentation/javascript/examples/polyline-remove for an example of how to implement this.
Updated demo: https://jsfiddle.net/3fe6nfdr/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With