Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling ctrl+click on Google Maps

I'm trying to make the user select multiple markers on my map by pressing control key and click on the marker.

For doing this, I write this code:

google.maps.event.addListener(marker, 'click', function (e) {
    // detect if is pressed ctrlKey or not to do stuff
}

In the GoogleMaps V3 docs there is no info or documentation about this e object, beyond the latLng property. But when I debug with Google Chrome, I see this Ra object that contains exactly what I needed. My question is, it is safe to hardcode this undocumented Ra access to obtain if ctrlKey is pressed?

enter image description here

like image 505
Agustin Meriles Avatar asked Feb 13 '14 15:02

Agustin Meriles


1 Answers

As asked for in comment, what contains Ra that is important? My experience is, that google maps change those internal variable / object names constantly.


However, had made a demo to show how to select multiple markers by holding ctrl down and clicking on the markers :

See fiddle -> http://jsfiddle.net/FbGa5/
Notice : You must activate the iframe by clicking on the map once before ctrl or any other keypress can be captured.

Keep track of the ctrl key :

var selecting = false,
    selectedMarkers = [];

window.onkeydown = function(e) {
  selecting = ((e.keyIdentifier == 'Control') || (e.ctrlKey == true));
}
window.onkeyup = function(e) {
  selecting = false;
}

Select markers if ctrl-key is down and a marker is clicked. If a marker is selected, it turns blue, if a marker is deselected it turns back to red :

google.maps.event.addListener(marker, 'click', function() {
   if (!selecting) return;
   var id = this.id;
   var index = selectedMarkers.indexOf(id);
   if (index>-1) {
     this.setIcon('https://maps.gstatic.com/mapfiles/ms2/micons/red-dot.png');
     selectedMarkers.splice(index, 1);
   } else {
     selectedMarkers.push(id);             
     this.setIcon('https://maps.gstatic.com/mapfiles/ms2/micons/blue-dot.png');
   }
});

Conclusion : You do not need Ra or any other argument in the marker click event in order to get it to work.

like image 149
davidkonrad Avatar answered Oct 06 '22 01:10

davidkonrad