I have Google Maps on my app and I use map for drawing Polyline on it. I want to listen keyboard events on Google map so that say if I pressed Esc key while drawing Polyline , it should stop drawing (it should reset DrawingMode). I tried this by 2 ways . 1. I added keyevents 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, event gets fired when I have clicked on map. But not when I am drawing on Map .
By adding event to Map itself
google.maps.event.addListener(me.map, 'keydown', function () {
alert('in keydown');
});
This never gets fired.`
And I dont want to listen key events on window or whole document as I have other components too in document
Any help? Thanks
You need to register a 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 realize that while this works for a rectangle, it doesn't seem to work with polygons because setting the drawing mode to null actually completes the overlay. In this case, you need to keep track of your overlay (in overlaycomplete
event) and call setMap(null)
on 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With