0
我希望用戶只有在按住CTRL鍵的情況下才能拖動標記。這可能嗎?是否可以在Google地圖中啓用CTRL +拖動標記?
我希望用戶只有在按住CTRL鍵的情況下才能拖動標記。這可能嗎?是否可以在Google地圖中啓用CTRL +拖動標記?
使用CTRL,ALT,或SHIFT很可能是有問題的,因爲這些鍵是由瀏覽器用來表示各種動作。不過,我想下面的例子中,結合中號鍵,以便在按下拖:
<!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>
測試在Firefox 3.6的Mac。但在Chrome上似乎並不能很順暢地工作,但我會樂觀地努力使其工作。