How to cancel a google map marker drag operation?
Asked Answered
C

2

9

As you see in the following code, the Markers are draggable. In some cases, If a marker is dropped in a wrong area(polygon) I would like to cancel the drop event and consequently the marker come back to its original location automatically.

function placeMarker(latlng, color, isDraggable) {
    var marker = new GMarker(latlng, { icon: getIcon(color), draggable: true });
    map.addOverlay(marker);
    GEvent.addListener(marker, "dragend", function () {
        //redraw polygons again
    });
    GEvent.addListener(marker, "click", function () {
        var latlng = marker.getPoint();
        map.openInfoWindowHtml(marker.getPoint(), latlng.y + ", " + latlng.x);
    });
    return marker;
}

The question is how can I cancel the drag event of marker when it's already dropped in dragend event?

Copt answered 26/2, 2011 at 23:32 Comment(3)
Why not just use an InfoWindow to show the marker's lat/lng, and not make the marker draggable at all?Humanoid
Just declare their draggable property as false and their clickable property as true. They will still listen to clicks and mouseover events.Downstairs
@MattBall I need to be draggable.Copt
C
3

Still couldn't find any solutions after these years, and yet again encountering this issue. I wish there was event.cancelDrag()to call.

All I can think of is to check if the marker belongs to mypolygon if not move it back to where it was before:

  • On dragstart save the current location as preLocation
  • on dragend use containsLocation(e.latLng, mypolygon)
    • yes => do nothing
    • no: set the marker location to preLocation.

google map containsLocation

google map Events

Copt answered 5/9, 2017 at 20:6 Comment(0)
G
1

I don't remember that Google Map API support it but you can serve this functionality for yourself by saving markers' movements to a stack and extracting old position when you need it. I know it isn't irrefragable answer. It just general idea. But I hope it will helpful.

Goldwin answered 27/2, 2011 at 0:0 Comment(2)
Really, why you don't whant to make the marker undraggable at all?Goldwin
That's the method which is implemented here: Duncan's blog -- Google Maps API – locked draggable markersBlowfly

© 2022 - 2024 — McMap. All rights reserved.