Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to cancel a Google Maps API polyline while it's being drawn?

I've built a Google Maps API toolset that allows the user to draw shapes over the map, give them names and record areas. On the completion of each shape, they are prompted to give it a name and set a few other options such as whether or not to show a label on the map.

I'd like to give the user the option to right click and cancel a polyline (or polygon) whilst placing the points, i.e. while they're drawing it.

Based on what I've read in the documentation, I should be able to detect that the user right clicked on the map, but I'm not sure how to cancel the overlay they were drawing, as it won't have been committed to the map yet, which means I won't be able to refer to it as an object.

Any ideas?

Solution

Thanks to Dr Molle for the solution, which was as follows:

    ...
    google.maps.event.addListener(_map, "rightclick", function(){
        InitialiseDrawingManager();
    });
}

function InitialiseDrawingManager(){
    if (_drawingManager != null)
        _drawingManager.setMap(null);

    _drawingManager = new google.maps.drawing.DrawingManager();
    _drawingManager.setMap(_map);

    UpdateOverlaySettings();
    ...
like image 651
Matt Winward Avatar asked Oct 24 '25 03:10

Matt Winward


1 Answers

While the code for the accepted answer works, it throws an error, probably due to event listeners not being removed properly.

The following is a better approach:

I used a variable cancelDrawingShape to detect if the Escape button has been pressed while stuff is being drawn. If the cancelDrawingShape is set to true, then I will remove the last drawn shape from the map.

var cancelDrawingShape = false;

google.maps.event.addListener(drawingManager, 'overlaycomplete', function (e) {
    var lastDrawnShape = e.overlay;
    if (cancelDrawingShape) {
        cancelDrawingShape = false;
        lastDrawnShape.setMap(null); // Remove drawn but unwanted shape
        return;
    }

    // Else, do other stuff with lastDrawnShape
});

$(document).keydown(function (event) {
    if (event.keyCode === 27) { // Escape key pressed
        cancelDrawingShape = true;
        drawingManager.setDrawingMode(null); // To terminate the drawing, will result in autoclosing of the shape being drawn.
    }
});
like image 71
Yangshun Tay Avatar answered Oct 26 '25 16:10

Yangshun Tay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!