代码之家  ›  专栏  ›  技术社区  ›  Andy

如何在Google Maps API上禁用箭头键平移

  •  0
  • Andy  · 技术社区  · 7 年前

    使用网页上的谷歌地图API,我可以使用键盘的上/下和右/左箭头键来平移地图。我希望允许用户像往常一样通过鼠标拖动/平移地图,但希望禁用在单击地图后通过键盘箭头按下进行的平移。我该怎么做?

    作为背景,我将网页上的箭头键用于其他功能(在HTML列表中上下移动),并且不希望在用户按下箭头键时地图四处移动。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Preston    7 年前

    您可以设置 keyboardShortcuts 中的选项 MapOptions false 禁用地图上的键盘操作

    Simple sample JSBin

    <!DOCTYPE html>
    <html>
      <head>
        <title>Simple Map</title>
        <meta name="viewport" content="initial-scale=1.0">
        <meta charset="utf-8">
        <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>
          var map;
          function initMap() {
            map = new google.maps.Map(document.getElementById('map'), {
              center: {lat: -34.397, lng: 150.644},
              keyboardShortcuts: false,
              gestureHandling: "greedy",
              zoom: 8
            });
          }
        </script>
        <script src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=YOUR_KEY"
        async defer></script>
      </body>
    </html>