I'd like the user to only be able to drag a marker when the CTRL key is held down. Is this possible?
+1
A:
Using CTRL, ALT, or SHIFT will probably be problematic, because these keys are used by the browsers to mean various actions. However, I tried the following example, binding the M key to allow dragging while being pressed:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps - Drag Marker while Key is Pressed</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 400px; height: 300px;"></div>
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var markerBounds = new google.maps.LatLngBounds();
var markers = [];
var i;
var createKeyHandler = function (type, keycode) {
return (function (e) {
var keyPress;
if (typeof event !== 'undefined') {
keyPress = event.keyCode;
}
else if (e) {
keyPress = e.which;
}
if (keyPress === keycode) {
for (i = 0; i < markers.length; i++) {
// while key is down, all markers are set to draggable = true
if (type === 'down') {
markers[i].setDraggable(true);
}
else {
markers[i].setDraggable(false);
}
}
}
return false; // Prevents the default action
});
};
// Add 10 random markers on the map
for (i = 0; i < 10; i++) {
markers.push(new google.maps.Marker({
map: map,
draggable: false,
position: new google.maps.LatLng( 39.00 + (Math.random() - 0.5) * 20,
-77.00 + (Math.random() - 0.5) * 20)
}));
markerBounds.extend(markers[markers.length - 1].getPosition());
}
// Adjust the map viewport to fit all the markers
map.fitBounds(markerBounds);
// Add event handlers for keydown and keyup
document.onkeydown = createKeyHandler('down', 77);
document.onkeyup = createKeyHandler('up', 77);
</script>
</body>
</html>
Tested in Firefox 3.6 for Mac. Doesn't seem to work very smoothly on Chrome however, but I would be optimistic in making it work with a little effort.
Daniel Vassallo
2010-09-28 23:18:42