Angela
Angela

Reputation: 41

jquery and google maps v3 dragstart and dragend

I am creating an array of markers and attaching functionality to dragstart and dragend. I finally got it to work with a simple change, but cannot understand why the original code I created does not work.

For each marker the following code runs:

google.maps.event.addListener(marker, 'dragstart', function(evt){
    GLOBAL.startDragPosition = this.getPosition();
});

google.maps.event.addListener(marker, 'dragend', function(evt){
    if (confirm("Are You Sure You Want To Move this marker NOW ??")) {
        //do something here ...
    } else {
        marker.setPosition(GLOBAL.startDragPosition);
        delete GLOBAL.startDragPosition;            
    }
});

If I cancel the move, a different marker moves back to the original location. If I change the else statement to the following it works -

    } else {
        this.setPosition(GLOBAL.startDragPosition);
        delete GLOBAL.startDragPosition;            
    }

Can anyone tell me why the "marker." notation is not referring to the marker being dragged?

TIA!!

Upvotes: 1

Views: 2695

Answers (1)

Jason Sperske
Jason Sperske

Reputation: 30446

This code:

google.maps.event.addListener(marker, 'dragend', function(evt){
    if (confirm("Are You Sure You Want To Move this marker NOW ??")) {
        //do something here ...
    } else {
        marker.setPosition(GLOBAL.startDragPosition);
        delete GLOBAL.startDragPosition;            
    }
});

Is not how closures work. The marker variable is not actually passed into the function(evt) {}. My hunch is you are defining marker some place else multiple times. Think of the function as a block of code that will be executed once a 'dragend' even is observed on the marker as it was defined when you set up the listener.

Upvotes: 1

Related Questions