ChatGPT解决这个技术问题 Extra ChatGPT

How to disable mouse scroll wheel scaling with Google Maps API

I am using Google Maps API (v3) to draw a few maps on a page. One thing I'd like to do is disable zooming when you scroll the mouse wheel over the map, but I'm unsure how.

I have disabled the scaleControl (i.e. removed the scaling UI element), but this doesn't prevent scroll wheel scaling.

Here is part of my function (it's a simple jQuery plugin):

$.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
};
Hi I created a more developed plugin that allows you to lock or unlock the map with a nice button. Also is jQuery plugin. You can check it at github.com/diazemiliano/googlemaps-scrollprevent I hope you like it.
Featured in Developers Writing the Future by Joel Spolsky (CEO & Co-founder of Stack Overflow), from 17 min 09 secs - 18 min 25 secs (2016-12-07).

u
user664833

In version 3 of the Maps API you can simply set the scrollwheel option to false within the MapOptions properties:

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

If you were using version 2 of the Maps API you would have had to use the disableScrollWheelZoom() API call as follows:

map.disableScrollWheelZoom();

The scrollwheel zooming is enabled by default in version 3 of the Maps API, but in version 2 it is disabled unless explicitly enabled with the enableScrollWheelZoom() API call.


+1 FYI: disableDefaultUI: true can replace navigationControl: false, mapTypeControl: false, scaleControl: false
A gotcha for me was that if you don't have the mapTypeId the other parameters are ignored.
This works for me, but it has the strange side effect of disabling the scroll wheel inside a modal on the page. There is no map in the modal content and the cursor is not over the map.
Sadly, this does not work as expected with StreetViewPanorama Map, as putting in scrollwheel: false, disables scroll zoom, but also disables scrolling the page as it is still catching the scroll somehow.
Daniel , Can you please help me in answering this question stackoverflow.com/questions/60544486/…
C
Community

Daniel's code does the job (thanks a heap!). But I wanted to disable zooming completely. I found I had to use all four of these options to do so:

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

See: MapOptions object specification


Does this still work for you? I've been unable to get the current version of v3 (I believe its 3.9) to ignore the scroll wheel, and had to resort to looping over all children of the map object and stopping propagation into the map.
Yup, works for me, thanks! Also, if you want to remove all default map control widgets, just do disableDefaultUI:true instead of turning off zoom, rotate and pan controls individually.
Beware capitalisation; scrollwheel needs to be all lower case (just caught me out by upcasing the W)
scrollwheel: false was all I needed
P
Peter Mortensen

Just in case you want to do this dynamically;

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

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

Sometimes you have to show something "complex" over the map (or the map is a small part of the layout), and this scroll zooming gets in the middle, but once you have a clean map, this way of zooming is nice.


You can add this code at initialization: map.addListener('click', function() { if(map) map.setOptions({ scrollwheel: true }); }); map.addListener('mouseout', function() { if(map) map.setOptions({ scrollwheel: false }); });
This works for me as I wanted to interrogate the map scrollwheel function outside of the google maps code. ie from inside my own jquery code.
t
tanguy_k

Keep it simple! Original Google maps variable, none of the extra stuff.

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

}

K
Kar.ma

As of now (October 2017) Google has implemented a specific property to handle the zooming/scrolling, called gestureHandling. Its purpose is to handle mobile devices operation, but it modifies the behaviour for desktop browsers as well. Here it is from 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: 'none' }); The available values for gestureHandling are: 'greedy': The map always pans (up or down, left or right) when the user swipes (drags on) the screen. In other words, both a one-finger swipe and a two-finger swipe cause the map to pan. 'cooperative': The user must swipe with one finger to scroll the page and two fingers to pan the map. If the user swipes the map with one finger, an overlay appears on the map, with a prompt telling the user to use two fingers to move the map. On desktop applications, users can zoom or pan the map by scrolling while pressing a modifier key (the ctrl or ⌘ key). 'none': This option disables panning and pinching on the map for mobile devices, and dragging of the map on desktop devices. 'auto' (default): Depending on whether the page is scrollable, the Google Maps JavaScript API sets the gestureHandling property to either 'cooperative' or 'greedy'

In short, you can easily force the setting to "always zoomable" ('greedy'), "never zoomable" ('none'), or "user must press CRTL/⌘ to enable zoom" ('cooperative').


E
Emiliano Díaz

I created a more developed jQuery plugin that allows you to lock or unlock the map with a nice button.

This plugin disables the Google Maps iframe with a transparent overlay div and adds a button for unlockit. You must press for 650 milliseconds to unlock it.

You can change all the options for your convenience. Check it at 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; }

"Start Scroll Prevent" "Stop Scroll Prevent"


nice plugin, but how to use it when you create the google map with the JS API instead of using an iframe?
Is "Edit in JSFiddle Result JavaScript HTML CSS" really part of the code?
P
Peter Mortensen

In my case the crucial thing was to set in 'scrollwheel':false in init. Notice: I am using jQuery UI Map. Below is my CoffeeScript init function heading:

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

P
Peter Mortensen

Just in case, you are using the GMaps.js library, which makes it a bit simpler to do things like Geocoding and custom pins, here's how you solve this issue using the techniques learned from the previous answers.

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 });
}

A
AlbertSamuel

For someone that wondering how to disable the Javascript Google Map API

It will enable the zooming scroll if you click the map once. And disable after your mouse exit the 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; }


K
Kiran Kanzar

You just need to add in map options:

scrollwheel: false

D
Darme

A simple solution:

// 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; }

Source: https://github.com/Corsidia/scrolloff


D
Davey

Just incase anybody is interested in a pure css solution for this. The following code overlays a transparent div over the map, and moves the transparent div behind the map when it is clicked. The overlay prevents zooming, once clicked, and behind the map, zooming is enabled.

See my blog post Google maps toggle zoom with css for an explanation how it works, and pen codepen.io/daveybrown/pen/yVryMr for a working demo.

Disclaimer: this is mainly for learning and probably won't be the best solution for production websites.

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;
}

C
Chamon Roy

Use that piece of code, that will give you all the color and zooming control of google map. (scaleControl: false and scrollwheel: false will prevent the mousewheel from zoom up or down)

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' }); }


While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. Please read this how-to-answer for providing quality answer.
d
dimitar

I do it with this simple examps

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, 

关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now