透過使用 MapOptions 物件中的 gestureHandling 選項,您可以控制在行動裝置上檢視地圖時的移動瀏覽與捲動行為。
範例
下列範例使用 cooperative 手勢處理方式。在行動裝置上檢視示範,以查看程式碼的運作方式。
/**
* This sample sets the gesture handling mode to 'cooperative',
* which means that on a mobile device, the user must swipe with one
* finger to scroll the page and two fingers to pan the map.
*/
function initMap() {
var myLatLng = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng,
gestureHandling: 'cooperative'
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
<div id="map"></div>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<!-- Replace the value of the key parameter with your own API key. --> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"> </script>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Cooperative Gesture Handling</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
/**
* This sample sets the gesture handling mode to 'cooperative',
* which means that on a mobile device, the user must swipe with one
* finger to scroll the page and two fingers to pan the map.
*/
function initMap() {
var myLatLng = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng,
gestureHandling: 'cooperative'
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
</html>
手勢處理方式
在使用行動裝置 Web 時,當使用者想要透過滑動來捲動頁面,卻變成使地圖平移時,可能會對他們造成困擾。
Google Maps JavaScript API 在 MapOptions 物件中提供 gestureHandling 選項,讓您可以用來最佳化使用者與地圖互動的體驗。可用的值為:
greedy:當使用者滑動(拖曳)畫面時,地圖一律會平移(向上或向下,向左或向右)。換句話說,單指滑動與兩指滑動都會使地圖平移。cooperative:使用者必須滑動單指以捲動頁面,以及滑動雙指以平移地圖。如果使用者以單指滑動地圖,地圖上方會出現疊加層,並以提示告知使用者以兩指來移動地圖。請在行動裝置上檢視上面的範例,以查看 cooperative 模式的運作方式。none:地圖無法平移或收縮。auto(預設):行為可能是cooperative或greedy,依該頁面是否可捲動而定。仔細來說,如果選項設定為auto,API 會選擇下列行為:cooperative:如果頁體比視窗還要大,或是如果 API 無法判斷頁面大小(例如,如果它位於 iframe 中)。greedy:如果頁體沒有視窗大,使用者不太可能需要捲動。
全螢幕控制項在行動裝置上預設為可見,因此使用者可以輕易地放大地圖。當地圖處於全螢幕模式時,使用者可以使用單指或兩指來平移地圖。注意:iOS 不支援全螢幕功能。因此,全螢幕控制項在 iOS 裝置上是不可見的。
事件
以下為 API 在使用者捲動(拖曳)地圖時會引發的某些事件:
drag:當使用者拖曳地圖時重複引發。dragstart:當使用者開始拖曳地圖時引發。dragend:當使用者停止拖曳地圖時引發。
限制
下列限制會套用到由 gestureHandling 選項所提供的行為:
