Search code examples
javascriptopenlayers

Openlayers and catching drag event


Im using OpenLayers and i need to be able to tell difference between when map has been moved by my own scrip or by user. Yeah im aware that i can use moveend. But it also triggers when the same script is moving or repositioning map based on incoming data from ajax calls. So moveend or other map events wont work.

I did some googling and found OpenLayers.Hander.Drag. But all that i managed with it was to stop users from dragging map.

My script:

this.dragger = new OpenLayers.Handler.Drag('',{
        'dragStart': function(evt){
            this.userdragged = true;
            console.log('drag');
        }},{
        'map':this.mymap
        });
this.dragger.activate();

As you can see, i tried to set userdragged variable to true to use this same variable in moveend event later. Unfortunately all this did was to stop my map from beeing draggable.

Can someone assist me please?

Alan


Solution

  • Got it!

    What got it working was :

    dragcontrol = new OpenLayers.Control.DragPan({'map':this.mymap, 'panMapDone':function(evt){
        this.userdragged  = true;
        console.log('drag');
    }});
    dragcontrol.draw();
    this.mymap.addControl(dragcontrol);
    dragcontrol.activate();
    

    Booyaka!

    Edit: Actually this.userdragged wont work in there... the scope of this is different there. you would need to do something like var that = this; before that object initialization and use that.userdragged = true....

    Edit2: I later found, that this panMapDone function overwrites DragPans own method which has same name. With just my previous example, you can end up with map that results in vector features going out of sync with map, when user drags map. To stop that from happening, you should copy the original functionality into that function too... to make it look something like that:

    dragcontrol = new OpenLayers.Control.DragPan({'map':this.mymap, 'panMapDone':function(xy){
            if(this.panned) {
                var res = null;
                if (this.kinetic) {
                    res = this.kinetic.end(xy);
                }
                this.map.pan(
                    this.handler.last.x - xy.x,
                    this.handler.last.y - xy.y,
                    {dragging: !!res, animate: false}
                );
                if (res) {
                    var self = this;
                    this.kinetic.move(res, function(x, y, end) {
                        self.map.pan(x, y, {dragging: !end, animate: false});
                    });
                }
                this.panned = false;
            }
            that.userdragged  = true;
                // do whatever you want here
        }});
        dragcontrol.draw();
        this.mymap.addControl(dragcontrol);
        dragcontrol.activate();
    

    Alan