首页 文章

如何使用Google Maps API禁用鼠标滚轮缩放

提问于
浏览
546

我正在使用Google Maps API(v3)在页面上绘制一些 Map . 我想做的一件事是在 Map 上滚动鼠标滚轮时禁用缩放,但我不确定如何 .

我已禁用scaleControl(即删除了缩放UI元素),但这不会阻止滚轮缩放 .

这是我的函数的一部分(它是一个简单的jQuery插件):

$.fn.showMap = function(options, addr){
  options = $.extend({
    navigationControl: false,
    mapTypeControl: false,
    scaleControl: false,
    draggable: false,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }, options);
  var map = new google.maps.Map(document.getElementById($(this).attr('id')), options);

  // Code cut from this example as not relevant
};

14 回答

  • 100

    在我的情况下,关键的是在init中设置 'scrollwheel':false . 注意:我正在使用jQuery UI Map . 下面是我的CoffeeScript init函数 Headers :

    $("#map_canvas").gmap({'scrollwheel':false}).bind "init", (evt, map) ->
    
  • 6

    只是因为有人对这个纯css解决方案感兴趣 . 以下代码在 Map 上覆盖透明div,并在单击时将透明div移动到 Map 后面 . 叠加可防止缩放,一旦单击,并在 Map 后面,即可启用缩放 .

    有关其工作原理的说明,请参阅我的博客文章Google maps toggle zoom with css,并查看工作演示的笔codepen.io/daveybrown/pen/yVryMr .

    免责声明:这主要用于学习,可能不是 生产环境 网站的最佳解决方案 .

    HTML:

    <div class="map-wrap small-11 medium-8 small-centered columns">
        <input id="map-input" type="checkbox" />
        <label class="map-overlay" for="map-input" class="label" onclick=""></label>
        <iframe src="https://www.google.com/maps/embed?pb=!1m14!1m12!1m3!1d19867.208601651986!2d-0.17101002911118332!3d51.50585742500925!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!5e0!3m2!1sen!2suk!4v1482355389969"></iframe>
    </div>
    

    CSS:

    .map-wrap {
        position: relative;
        overflow: hidden;
        height: 180px;
        margin-bottom: 10px;
    }
    
    #map-input {
        opacity: 0;
    }
    
    .map-overlay {
        display: block;
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100% !important;
        height: 100% !important;
        overflow: hidden;
        z-index: 2;    
    }
    
    #map-input[type=checkbox]:checked ~ iframe {
        z-index: 3;
    }
    
    #map-input[type=checkbox]:checked ~ .map-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100% !important;
        height: 100% !important;
    }
    
    
    iframe {
        position: absolute;
        top: 0;
        left: 0;
        width: 100% !important;
        height: 100% !important;
        z-index: 1;
        border: none;
    }
    
  • 4

    您只需添加 Map 选项:

    scrollwheel: false
    
  • 0

    以防万一,您正在使用GMaps.js库,这使得执行地理编码和自定义引脚等操作变得更加简单,以下是使用从先前答案中学习的技术解决此问题的方法 .

    var Gmap = new GMaps({
      div: '#main-map', // FYI, this setting property used to be 'el'. It didn't need the '#' in older versions
      lat: 51.044308,
      lng: -114.0630914,
      zoom: 15
    });
    
    // To access the Native Google Maps object use the .map property
    if(Gmap.map) {
      // Disabling mouse wheel scroll zooming
      Gmap.map.setOptions({ scrollwheel: false });
    }
    
  • 0

    使用那段代码,它将为您提供谷歌 Map 的所有颜色和缩放控制 . ( scaleControl: falsescrollwheel: false 将阻止鼠标滚轮向上或向下缩放)

    function initMap() {
                // Styles a map in night mode.
                var map = new google.maps.Map(document.getElementById('map'), {
                    center: {lat: 23.684994, lng: 90.356331},
                    zoom: 8,
                    scaleControl: false,
                    scrollwheel: false,
                  styles: [
                    {elementType: 'geometry', stylers: [{color: 'F1F2EC'}]},
                    {elementType: 'labels.text.stroke', stylers: [{color: '877F74'}]},
                    {elementType: 'labels.text.fill', stylers: [{color: '877F74'}]},
                    {
                      featureType: 'administrative.locality',
                      elementType: 'labels.text.fill',
                      stylers: [{color: '#d59563'}]
                    },
                    {
                      featureType: 'poi',
                      elementType: 'labels.text.fill',
                      stylers: [{color: '#d59563'}]
                    },
                    {
                      featureType: 'poi.park',
                      elementType: 'geometry',
                      stylers: [{color: '#263c3f'}]
                    },
                    {
                      featureType: 'poi.park',
                      elementType: 'labels.text.fill',
                      stylers: [{color: '#f77c2b'}]
                    },
                    {
                      featureType: 'road',
                      elementType: 'geometry',
                      stylers: [{color: 'F5DAA6'}]
                    },
                    {
                      featureType: 'road',
                      elementType: 'geometry.stroke',
                      stylers: [{color: '#212a37'}]
                    },
                    {
                      featureType: 'road',
                      elementType: 'labels.text.fill',
                      stylers: [{color: '#f77c2b'}]
                    },
                    {
                      featureType: 'road.highway',
                      elementType: 'geometry',
                      stylers: [{color: '#746855'}]
                    },
                    {
                      featureType: 'road.highway',
                      elementType: 'geometry.stroke',
                      stylers: [{color: 'F5DAA6'}]
                    },
                    {
                      featureType: 'road.highway',
                      elementType: 'labels.text.fill',
                      stylers: [{color: 'F5DAA6'}]
                    },
                    {
                      featureType: 'transit',
                      elementType: 'geometry',
                      stylers: [{color: '#2f3948'}]
                    },
                    {
                      featureType: 'transit.station',
                      elementType: 'labels.text.fill',
                      stylers: [{color: '#f77c2b3'}]
                    },
                    {
                      featureType: 'water',
                      elementType: 'geometry',
                      stylers: [{color: '#0676b6'}]
                    },
                    {
                      featureType: 'water',
                      elementType: 'labels.text.fill',
                      stylers: [{color: '#515c6d'}]
                    },
                    {
                      featureType: 'water',
                      elementType: 'labels.text.stroke',
                      stylers: [{color: '#17263c'}]
                    }
                  ]
                });
        
                 var marker = new google.maps.Marker({
                  position: {lat: 23.684994, lng: 90.356331},
                  map: map,
                  title: 'BANGLADESH'
                });
              }
    
  • 29

    我用这个简单的例子做到了

    jQuery

    $('.map').click(function(){
        $(this).find('iframe').addClass('clicked')
        }).mouseleave(function(){
        $(this).find('iframe').removeClass('clicked')
    });
    

    CSS

    .map {
        width: 100%; 
    }
    .map iframe {
        width: 100%;
        display: block;
        pointer-events: none;
        position: relative; /* IE needs a position other than static */
    }
    .map iframe.clicked {
        pointer-events: auto;
    }
    

    Or use the gmap options

    function init() { 
        var mapOptions = {  
            scrollwheel: false,
    
  • 6

    在Maps API的第3版中,您只需在MapOptions属性中将 scrollwheel 选项设置为false:

    options = $.extend({
        scrollwheel: false,
        navigationControl: false,
        mapTypeControl: false,
        scaleControl: false,
        draggable: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }, options);
    

    如果您使用的是Maps API的第2版,则必须使用disableScrollWheelZoom() API调用,如下所示:

    map.disableScrollWheelZoom();
    

    默认情况下,在Maps API的版本3中启用了 scrollwheel 缩放,但在版本2中,除非使用 enableScrollWheelZoom() API调用明确启用,否则它将被禁用 .

  • 6

    对于想知道如何禁用 Javascript Google Map API 的人

    如果您单击一次 Map ,它将 enable 缩放滚动 . 并且 disable 在鼠标退出div之后 .

    Here is some example

    var map;
    var element = document.getElementById('map-canvas');
    function initMaps() {
      map = new google.maps.Map(element , {
        zoom: 17,
        scrollwheel: false,
        center: {
          lat: parseFloat(-33.915916),
          lng: parseFloat(151.147159)
        },
      });
    }
    
    
    //START IMPORTANT part
    //disable scrolling on a map (smoother UX)
    jQuery('.map-container').on("mouseleave", function(){
      map.setOptions({ scrollwheel: false });
    });
    jQuery('.map-container').on("mousedown", function() {
      map.setOptions({ scrollwheel: true });
    });
    //END IMPORTANT part
    
    .big-placeholder {
      background-color: #1da261;
      height: 300px;
    }
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <html>
      <body>
          <div class="big-placeholder">
          </div>
          
          
          <!-- START IMPORTANT part -->
          <div class="map-container">
            <div id="map-canvas" style="min-height: 400px;"></div>  
          </div>
          <!-- END IMPORTANT part-->
          
          
          
          <div class="big-placeholder">
          </div>
          <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAIjN23OujC_NdFfvX4_AuoGBbkx7aHMf0&callback=initMaps">
          </script>
      </body>
    </html>
    
  • 969

    我创建了一个更加开发的jQuery插件,允许您使用一个漂亮的按钮锁定或解锁 Map .

    此插件会禁用带有透明叠加div的Google Maps iframe,并为unlockit添加一个按钮 . 您必须按下650毫秒才能解锁它 .

    您可以更改所有选项以方便使用 . 在https://github.com/diazemiliano/googlemaps-scrollprevent查看

    Here's some example.

    (function() {
      $(function() {
        $("#btn-start").click(function() {
          $("iframe[src*='google.com/maps']").scrollprevent({
            printLog: true
          }).start();
          return $("#btn-stop").click(function() {
            return $("iframe[src*='google.com/maps']").scrollprevent().stop();
          });
        });
        return $("#btn-start").trigger("click");
      });
    }).call(this);
    
    .embed-container {
      position: relative !important;
      padding-bottom: 56.25% !important;
      height: 0 !important;
      overflow: hidden !important;
      max-width: 100% !important;
    }
    .embed-container iframe {
      position: absolute !important;
      top: 0 !important;
      left: 0 !important;
      width: 100% !important;
      height: 100% !important;
    }
    .mapscroll-wrap {
      position: static !important;
    }
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="https://cdn.rawgit.com/diazemiliano/googlemaps-scrollprevent/v.0.6.5/dist/googlemaps-scrollprevent.min.js"></script>
    <div class="embed-container">
      <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d12087.746318586604!2d-71.64614110000001!3d-40.76341959999999!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x9610bf42e48faa93%3A0x205ebc786470b636!2sVilla+la+Angostura%2C+Neuqu%C3%A9n!5e0!3m2!1ses-419!2sar!4v1425058155802"
      width="400" height="300" frameborder="0" style="border:0"></iframe>
    </div>
    <p><a id="btn-start" href="#">"Start Scroll Prevent"</a>  <a id="btn-stop" href="#">"Stop Scroll Prevent"</a>
    </p>
    
  • 2

    简单的解决方案:

    // DISABLE MOUSE SCROLL IN MAPS
    // enable the pointer events only on click;
    $('.gmap-wrapper').on('click', function () {
      $('.gmap-wrapper iframe').removeClass('scrolloff'); // set the pointer events true on click
    });
    // you want to disable pointer events when the mouse leave the canvas area;
    $(".gmap-wrapper").mouseleave(function () {
      $('.gmap-wrapper iframe').addClass('scrolloff'); // set the pointer events to none when mouse leaves the map area
    });
    
    .scrolloff{ pointer-events: none; }
    
    <html>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div class="gmap-wrapper">
    <iframe class="scrolloff" src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d44754.55736493158!2d9.151166379101554!3d45.486726!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x4786bfca7e8fb1cb%3A0xee8d99c9d153be98!2sCorsidia!5e0!3m2!1sit!2sit!4v1496947992608" width="600" height="450" frameborder="0" style="border:0" allowfullscreen></iframe>
    </div>
    </html>
    

    资料来源:https://github.com/Corsidia/scrolloff

  • 6

    Daniel's code完成工作(感谢一堆!) . 但我想完全禁用缩放 . 我发现我必须使用所有这四个选项才能这样做:

    {
      zoom: 14,                        // Set the zoom level manually
      zoomControl: false,
      scaleControl: false,
      scrollwheel: false,
      disableDoubleClickZoom: true,
      ...
    }
    

    见:MapOptions object specification

  • 4

    把事情简单化!原始谷歌 Map 变量,没有额外的东西 .

    var mapOptions = {
         zoom: 16,
         center: myLatlng,
         scrollwheel: false
    
    }
    
  • 2

    以防你想动态地这样做;

    function enableScrollwheel(map) {
        if(map) map.setOptions({ scrollwheel: true });
    }
    
    function disableScrollwheel(map) {
        if(map) map.setOptions({ scrollwheel: false });
    }
    

    有时你必须在 Map 上显示一些“复杂”的东西(或者 Map 是布局的一小部分),这个滚动缩放位于中间,但是一旦你有了一个干净的 Map ,这种缩放方式就很好了 .

  • 26

    截至目前(2017年10月),Google已经实现了一个特定属性来处理缩放/滚动,称为 gestureHandling . 其目的是处理移动设备操作,但它也会修改桌面浏览器的行为 . 这是official documentation

    function initMap(){
    var locationRio = {lat:-22.915,lng:-43.197};
    var map = new google.maps.Map(document.getElementById('map'),{
    zoom:13,
    center:locationRio,
    gestureHandling:'无'
    });
    gestureHandling的可用值为:'贪婪':当用户滑动(拖动)屏幕时, Map 始终平移(向上或向下,向左或向右) . 换句话说,单指滑动和双指滑动都会导致 Map 平移 . '合作':用户必须用一根手指滑动才能滚动页面和两根手指来平移 Map . 如果用户用一根手指滑动 Map , Map 上会出现一个叠加层,并提示用户使用两根手指移动 Map . 在桌面应用程序上,用户可以在按下修改键(ctrl或⌘键)的同时滚动来缩放或平移 Map . 'none':此选项禁用移动设备 Map 上的平移和捏合,以及在桌面设备上拖动 Map . 'auto'(默认值):根据页面是否可滚动,Google Maps JavaScript API将gestureHandling属性设置为“合作”或“贪婪”

    简而言之,您可以轻松地将设置强制设置为"always zoomable"( 'greedy' ),"never zoomable"( 'none' )或"user must press CRTL/⌘ to enable zoom"( 'cooperative' ) .

相关问题