[GIS] How to use right-click to finish drawing a Polygon in OpenLayers

javascriptopenlayers-2

I'm using OpenLayers 2.13 and the DrawFeature control. By Default, the Polygon is completed, when you double click.

Some of our clients are requesting that we allow the mouse right-click, to finish the polygon.

I tried adding a rightclick function to the OpenLayers.Handler.Polygon class, but it is never called.

I also confirmed that the right click event is being registered in the activate method of the OpenLayers.Handler class.

How do I override this behavior to allow the mouse right-click to finish the polygon?

Best Answer

I just ran into this problem myself. There are a couple of steps to take to get the right-click events working.

There seems to be a piece of logic implemented solely for the Navigation tool in the Click handler class. This checks to see if the control associated with the handler has a handleRightClicks property set to true.

https://github.com/openlayers/openlayers/blob/master/lib/OpenLayers/Handler/Click.js

215        if (this.checkModifiers(evt) && this.control.handleRightClicks &&

So you need to add a handleRightClicks property to your DrawFeature control and set to true.

To prevent the browser's context menu from appearing when right clicking, you also need to include the following line of JavaScript:

    this.map.viewPortDiv.oncontextmenu = OpenLayers.Function.False;

This above line is used in the Navigation control.

Then you should be able to create a handler in your control similar to:

            var handlerOptions = {
                'single': true,
                'double': true
            };

            this.handlers = {
                click: new OpenLayers.Handler.Click(this, {
                    'click': this.onClick,
                    'rightclick': this.onRightClick,
                    'dblrightclick': this.onRightClick
                }, handlerOptions)
            };

The documents state that only the Click handler only supports callbacks for click and doubleclick, but this is not the case - rightclick and dblrightclick also work.