Listen to keyboard events in Google Map

I have Google Maps in my application, and I use the map to draw Polyline on it. I want to listen to keyboard events on a Google map to say that if I press the Esc key while drawing a polyline, it should stop drawing (it should reset DrawingMode). I tried this in two ways. 1. I added key events to its container:

bindKeyEventsForMapButtons : function(btn){ var me = this; btn.el.dom.onkeydown = function (e) { if(btn.getId() == 'drawPerimeterGoogleMap'){ if(btn.pressed==true) btn.toggle(false); }else if(btn.getId() == 'removeAllPerimeter'){ btn.setPressed(false); } } } 

In this case, the event fires when I click on the map. But not when I draw a map.

  1. Adding an event to the map itself

    google.maps.event.addListener(me.map, 'keydown', function () { alert('in keydown'); });

It never works.

And I don’t want to listen to key events in the window or the whole document, since I have other components in the document

Any help? Thanks

+5
source share
1 answer

You need to register the DOM event listener addDomListener and call setDrawingMode(null) on the drawingManager .

 google.maps.event.addDomListener(document, 'keyup', function (e) { var code = (e.keyCode ? e.keyCode : e.which); if (code === 27) { drawingManager.setDrawingMode(null); } }); 

Below is a working demo. Hope this helps.

Jsfiddle demo

Edit

I understand that although this works for a rectangle, it does not seem to work with polygons because setting the paint mode to zero actually completes the overlay. In this case, you need to track your overlay (in the overlaycomplete event) and call setMap(null) in the polygon itself in addition to the above.

 var polygon; google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) { polygon = e.overlay; }); google.maps.event.addDomListener(document, 'keyup', function (e) { var code = (e.keyCode ? e.keyCode : e.which); if (code === 27) { drawingManager.setDrawingMode(null); polygon.setMap(null); } }); 

Jsfiddle demo

+5
source

Source: https://habr.com/ru/post/1213024/


All Articles