禁用嵌入式谷歌地图中的鼠标滚轮缩放

202

我正在处理一个WordPress网站,作者通常在大多数文章中使用iFrames嵌入Google地图。

是否有一种使用Javascript在所有这些地图上禁用鼠标滚轮缩放的方法?


32
将地图选项中的 scrollwheel 设为 false - Anto Jurković
或者通过JS直接禁用它:map.disableScrollWheelZoom(); - Th3Alchemist
4
很抱歉,由于安全限制,无法对地图进行脚本访问。据我所知,也没有可用的URL参数来禁用它。我不能为你做到这一点。 - Dr.Molle
有完全相同的问题。想要禁用嵌入iframe地图上的鼠标滚动事件。但还没有找到解决方法。 - Grzegorz
8
这是嵌入式地图,不确定为什么有人发布使用Maps JS库的解决方案。 - zanderwar
30个回答

1

我自己遇到了这个问题,使用了这个问题上两个非常有用的答案的混合体:czerasz的答案和massa的答案。

他们都有很多道理,但在我的测试中,我发现其中一个在移动设备上无法正常工作,并且在IE上支持不佳(仅适用于IE11)。这是nathanielperales提出的解决方案,然后由czerasz扩展,它依赖于指针事件css,在移动设备上无法工作(移动设备没有指针),并且它不适用于任何不是v11的IE版本。通常我不会太在意,但有大量的用户,我们需要一致的功能,因此我选择了叠加层解决方案,使用包装器使其更易于编码。

所以,我的标记看起来像这样:

<div class="map embed-container">
  <div id="map-notice" style="display: block;"> {Tell your users what to do!} </div>
  <div class="map-overlay" style="display: block;"></div>
  <iframe style="width:100%" src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d3785.684302567802!2d-66.15578327375803!3d18.40721382009222!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x8c036a35d02b013f%3A0x5962cad95b9ec7f8!2sPlaza+Del+Sol!5e0!3m2!1sen!2spr!4v1415284687548" width="633" height="461" frameborder="0"></iframe>
</div>

然后样式就像这样:

.map.embed-container {
  position:relative;
}

.map.embed-container #map-notice{
  position:absolute;
  right:0;
  top:0;
  background-color:rgb(100,100,100);/*for old IE browsers with no support for rgba()*/
  background-color: rgba(0,0,0,.50);
  color: #ccc;
  padding: 8px;
}
.map.embed-container .map-overlay{
  height:100%;
  width:100%;
  position:absolute;
  z-index:9999;
  background-color:rgba(0,0,0,0.10);/*should be transparent but this will help you see where the overlay is going in relation with the markup*/
}

最后是脚本:

//using jquery...
var onMapMouseleaveHandler = function (event) {
  $('#map-notice').fadeIn(500);
  var elemento = $$(this);
  elemento.on('click', onMapClickHandler);
  elemento.off('mouseleave', onMapMouseleaveHandler);
  $('.map-overlay').fadeIn(500);
}

var onMapClickHandler = function (event) {
  $('#map-notice').fadeOut(500);
  var elemento = $$(this);
  elemento.off('click', onMapClickHandler);
  $('.map-overlay').fadeOut(500);
  elemento.on('mouseleave', onMapMouseleaveHandler);
}
$('.map.embed-container').on('click', onMapClickHandler);

如果您想从那里获取相关内容,我还在GitHub gist中添加了我的测试解决方案...


1
在Google Maps v3中,您现在可以禁用滚动缩放功能,这将带来更好的用户体验。其他地图功能仍将正常工作,您不需要额外的div。我还认为应该为用户提供一些反馈,以便他们可以看到何时启用了滚动功能,因此我添加了地图边框。
// map is the google maps object, '#map' is the jquery selector
preventAccidentalZoom(map, '#map'); 

// Disables and enables scroll to zoom as appropriate. Also
// gives the user a UI cue as to when scrolling is enabled.
function preventAccidentalZoom(map, mapSelector){
  var mapElement = $(mapSelector);

  // Disable the scroll wheel by default
  map.setOptions({ scrollwheel: false })

  // Enable scroll to zoom when there is a mouse down on the map.
  // This allows for a click and drag to also enable the map
  mapElement.on('mousedown', function () {
    map.setOptions({ scrollwheel: true });
    mapElement.css('border', '1px solid blue')
  });

  // Disable scroll to zoom when the mouse leaves the map.
  mapElement.mouseleave(function () {
    map.setOptions({ scrollwheel: false })
    mapElement.css('border', 'none')
  });
};

1
这是一个使用CSS和Javascript(即Jquery,但也可使用纯Javascript)的解决方案。同时地图具有响应式设计。避免地图在滚动时缩放,但可以通过点击激活地图。
HTML / JQuery Javascript
<div id="map" onclick="$('#googlemap').css('pointerEvents','auto'); return true;"> 
    <iframe id="googlemap" src="http://your-embed-url" height="350"></iframe>
</div>

CSS

#map {
    position: relative; 
    padding-bottom: 36%; /* 16:9 ratio for responsive */ 
    height: 0; 
    overflow: hidden; 
    background:transparent; /* does the trick */
    z-index:98; /* does the trick */
}
#map iframe { 
    pointer-events:none; /* does the trick */
    position: absolute; 
    top: 0; 
    left: 0; 
    width: 100% !important; 
    height: 100% !important; 
    z-index:97; /* does the trick */
} 

玩得开心!


0

最简单的方法:

<div id="myIframe" style="width:640px; height:480px;">
   <div style="background:transparent; position:absolute; z-index:1; width:100%; height:100%; cursor:pointer;" onClick="style.pointerEvents='none'"></div>
   <iframe src="https://www.google.com/maps/d/embed?mid=XXXXXXXXXXXXXX" style="width:640px; height:480px;"></iframe>
</div>

这个小小的绝对定位 div 对我的使用情况非常有效,谢谢。 - Dan

0
如果您有一个使用Google地图嵌入式API的iframe,就像这样:
 <iframe width="320" height="400" frameborder="0" src="https://www.google.com/maps/embed/v1/place?q=Cagli ... "></iframe>

你可以添加这个CSS样式:pointer-event:none;

<iframe width="320" height="400" frameborder="0" style="pointer-event:none;" src="https://www.google.com/maps/embed/v1/place?q=Cagli ... "></iframe>

0
这是我的看法,基于 @nathanielperales 的答案,由 @chams 扩展,现在我再次扩展。
HTML
<div class='embed-container maps'>
    <iframe width='600' height='450' frameborder='0' src='http://foo.com'></iframe>
</div> 

jQuery

// we're doing so much with jQuery already, might as well set the initial state
$('.maps iframe').css("pointer-events", "none");

// as a safety, allow pointer events on click
$('.maps').click(function() {
  $(this).find('iframe').css("pointer-events", "auto");
});


$('.maps').mouseleave(function() {
  // set the default again on mouse out - disallow pointer events
  $(this).find('iframe').css("pointer-events", "none");
  // unset the comparison data so it doesn't effect things when you enter again
  $(this).removeData('oldmousepos');
});

$('.maps').bind('mousemove', function(e){
  $this = $(this);
  // check the current mouse X position
  $this.data('mousepos', e.pageX);
  // set the comparison data if it's null or undefined
  if ($this.data('oldmousepos') == null) {
    $this.data('oldmousepos', $this.data('mousepos'));
  }
  setTimeout(function(){
    // some left/right movement - allow pointer events
    if ($this.data('oldmousepos') != $this.data('mousepos')) {
      $this.find('iframe').css("pointer-events", "auto");
    }
    // set the compairison variable
    $this.data('oldmousepos', $this.data('mousepos'));
  }, 300);
  console.log($this.data('oldmousepos')+ ' ' + $this.data('mousepos'));
});

0
这是我的解决方案。
将以下代码添加到我的 main.js 或类似的文件中:
// Create an array of styles.
var styles = [
                {
                    stylers: [
                        { saturation: -300 }

                    ]
                },{
                    featureType: 'road',
                    elementType: 'geometry',
                    stylers: [
                        { hue: "#16a085" },
                        { visibility: 'simplified' }
                    ]
                },{
                    featureType: 'road',
                    elementType: 'labels',
                    stylers: [
                        { visibility: 'off' }
                    ]
                }
              ],

                // Lagitute and longitude for your location goes here
               lat = -7.79722,
               lng = 110.36880,

              // Create a new StyledMapType object, passing it the array of styles,
              // as well as the name to be displayed on the map type control.
              customMap = new google.maps.StyledMapType(styles,
                  {name: 'Styled Map'}),

            // Create a map object, and include the MapTypeId to add
            // to the map type control.
              mapOptions = {
                  zoom: 12,
                scrollwheel: false,
                  center: new google.maps.LatLng( lat, lng ),
                  mapTypeControlOptions: {
                      mapTypeIds: [google.maps.MapTypeId.ROADMAP],

                  }
              },
              map = new google.maps.Map(document.getElementById('map'), mapOptions),
              myLatlng = new google.maps.LatLng( lat, lng ),

              marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                icon: "images/marker.png"
              });

              //Associate the styled map with the MapTypeId and set it to display.
              map.mapTypes.set('map_style', customMap);
              map.setMapTypeId('map_style');

然后,在您希望地图出现在页面上的位置插入一个空的 div。

<div id="map"></div>

您显然还需要调用 Google Maps API。我只是创建了一个名为 mapi.js 的文件并将其放入我的 /js 文件夹中。此文件需要在上述 JavaScript 之前调用。

`window.google = window.google || {};
google.maps = google.maps || {};
(function() {

  function getScript(src) {
    document.write('<' + 'script src="' + src + '"' +
                   ' type="text/javascript"><' + '/script>');
  }

  var modules = google.maps.modules = {};
  google.maps.__gjsload__ = function(name, text) {
    modules[name] = text;
  };

  google.maps.Load = function(apiLoad) {
    delete google.maps.Load;
    apiLoad([0.009999999776482582,[[["http://mt0.googleapis.com/vt?lyrs=m@228000000\u0026src=api\u0026hl=en-US\u0026","http://mt1.googleapis.com/vt?lyrs=m@228000000\u0026src=api\u0026hl=en-US\u0026"],null,null,null,null,"m@228000000"],[["http://khm0.googleapis.com/kh?v=135\u0026hl=en-US\u0026","http://khm1.googleapis.com/kh?v=135\u0026hl=en-US\u0026"],null,null,null,1,"135"],[["http://mt0.googleapis.com/vt?lyrs=h@228000000\u0026src=api\u0026hl=en-US\u0026","http://mt1.googleapis.com/vt?lyrs=h@228000000\u0026src=api\u0026hl=en-US\u0026"],null,null,null,null,"h@228000000"],[["http://mt0.googleapis.com/vt?lyrs=t@131,r@228000000\u0026src=api\u0026hl=en-US\u0026","http://mt1.googleapis.com/vt?lyrs=t@131,r@228000000\u0026src=api\u0026hl=en-US\u0026"],null,null,null,null,"t@131,r@228000000"],null,null,[["http://cbk0.googleapis.com/cbk?","http://cbk1.googleapis.com/cbk?"]],[["http://khm0.googleapis.com/kh?v=80\u0026hl=en-US\u0026","http://khm1.googleapis.com/kh?v=80\u0026hl=en-US\u0026"],null,null,null,null,"80"],[["http://mt0.googleapis.com/mapslt?hl=en-US\u0026","http://mt1.googleapis.com/mapslt?hl=en-US\u0026"]],[["http://mt0.googleapis.com/mapslt/ft?hl=en-US\u0026","http://mt1.googleapis.com/mapslt/ft?hl=en-US\u0026"]],[["http://mt0.googleapis.com/vt?hl=en-US\u0026","http://mt1.googleapis.com/vt?hl=en-US\u0026"]],[["http://mt0.googleapis.com/mapslt/loom?hl=en-US\u0026","http://mt1.googleapis.com/mapslt/loom?hl=en-US\u0026"]],[["https://mts0.googleapis.com/mapslt?hl=en-US\u0026","https://mts1.googleapis.com/mapslt?hl=en-US\u0026"]],[["https://mts0.googleapis.com/mapslt/ft?hl=en-US\u0026","https://mts1.googleapis.com/mapslt/ft?hl=en-US\u0026"]]],["en-US","US",null,0,null,null,"http://maps.gstatic.com/mapfiles/","http://csi.gstatic.com","https://maps.googleapis.com","http://maps.googleapis.com"],["http://maps.gstatic.com/intl/en_us/mapfiles/api-3/14/0","3.14.0"],[2635921922],1,null,null,null,null,0,"",null,null,0,"http://khm.googleapis.com/mz?v=135\u0026",null,"https://earthbuilder.googleapis.com","https://earthbuilder.googleapis.com",null,"http://mt.googleapis.com/vt/icon",[["http://mt0.googleapis.com/vt","http://mt1.googleapis.com/vt"],["https://mts0.googleapis.com/vt","https://mts1.googleapis.com/vt"],[null,[[0,"m",228000000]],[null,"en-US","US",null,18,null,null,null,null,null,null,[[47],[37,[["smartmaps"]]]]],0],[null,[[0,"m",228000000]],[null,"en-US","US",null,18,null,null,null,null,null,null,[[47],[37,[["smartmaps"]]]]],3],[null,[[0,"h",228000000]],[null,"en-US","US",null,18,null,null,null,null,null,null,[[50],[37,[["smartmaps"]]]]],0],[null,[[0,"h",228000000]],[null,"en-US","US",null,18,null,null,null,null,null,null,[[50],[37,[["smartmaps"]]]]],3],[null,[[4,"t",131],[0,"r",131000000]],[null,"en-US","US",null,18,null,null,null,null,null,null,[[5],[37,[["smartmaps"]]]]],0],[null,[[4,"t",131],[0,"r",131000000]],[null,"en-US","US",null,18,null,null,null,null,null,null,[[5],[37,[["smartmaps"]]]]],3],[null,null,[null,"en-US","US",null,18],0],[null,null,[null,"en-US","US",null,18],3],[null,null,[null,"en-US","US",null,18],6],[null,null,[null,"en-US","US",null,18],0]]], loadScriptTime);
  };
  var loadScriptTime = (new Date).getTime();
  getScript("http://maps.gstatic.com/intl/en_us/mapfiles/api-3/14/0/main.js");
})();`

当您调用mapi.js文件时,请确保将其传递给sensor false属性。

例如:<script type="text/javascript" src="js/mapi.js?sensor=false"></script>

API的新版本3需要包含某些原因的传感器。请确保在main.js文件之前包含mapi.js文件。


0

对于 Google 地图 V2 - GMap2:

ar map = new GMap2(document.getElementById("google_map"));
map.disableScrollWheelZoom();

0

-1
这是关于编程的内容。以下是翻译:

这是我的问题解决方案,我正在构建一个WordPress网站,因此这里有一些PHP代码。但关键是在地图对象中使用scrollwheel: false

function initMap() {
        var uluru = {lat: <?php echo $latitude; ?>, lng: <?php echo $Longitude; ?>};
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 18,
            scrollwheel: false,
            center: uluru
        });
        var marker = new google.maps.Marker({
            position: uluru,
            map: map
        });
    }

希望这可以帮助到您。 干杯

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接