在移动设备上查看地图时,可以利用 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>
手势处理
在移动网络上,如果用户滑动手指滚动页面时地图却意外地平移,会很令人恼火。
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 选项提供的行为受到以下限制:
