[jquery] 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
};

This question is related to jquery google-maps google-maps-api-3 jquery-plugins

The answer is


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, 

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

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


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

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


A simple solution:

_x000D_
_x000D_
// DISABLE MOUSE SCROLL IN MAPS_x000D_
// enable the pointer events only on click;_x000D_
$('.gmap-wrapper').on('click', function () {_x000D_
  $('.gmap-wrapper iframe').removeClass('scrolloff'); // set the pointer events true on click_x000D_
});_x000D_
// you want to disable pointer events when the mouse leave the canvas area;_x000D_
$(".gmap-wrapper").mouseleave(function () {_x000D_
  $('.gmap-wrapper iframe').addClass('scrolloff'); // set the pointer events to none when mouse leaves the map area_x000D_
});
_x000D_
.scrolloff{ pointer-events: none; }
_x000D_
<html>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class="gmap-wrapper">_x000D_
<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>_x000D_
</div>_x000D_
</html>
_x000D_
_x000D_
_x000D_

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


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

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.

_x000D_
_x000D_
(function() {_x000D_
  $(function() {_x000D_
    $("#btn-start").click(function() {_x000D_
      $("iframe[src*='google.com/maps']").scrollprevent({_x000D_
        printLog: true_x000D_
      }).start();_x000D_
      return $("#btn-stop").click(function() {_x000D_
        return $("iframe[src*='google.com/maps']").scrollprevent().stop();_x000D_
      });_x000D_
    });_x000D_
    return $("#btn-start").trigger("click");_x000D_
  });_x000D_
}).call(this);
_x000D_
.embed-container {_x000D_
  position: relative !important;_x000D_
  padding-bottom: 56.25% !important;_x000D_
  height: 0 !important;_x000D_
  overflow: hidden !important;_x000D_
  max-width: 100% !important;_x000D_
}_x000D_
.embed-container iframe {_x000D_
  position: absolute !important;_x000D_
  top: 0 !important;_x000D_
  left: 0 !important;_x000D_
  width: 100% !important;_x000D_
  height: 100% !important;_x000D_
}_x000D_
.mapscroll-wrap {_x000D_
  position: static !important;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://cdn.rawgit.com/diazemiliano/googlemaps-scrollprevent/v.0.6.5/dist/googlemaps-scrollprevent.min.js"></script>_x000D_
<div class="embed-container">_x000D_
  <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"_x000D_
  width="400" height="300" frameborder="0" style="border:0"></iframe>_x000D_
</div>_x000D_
<p><a id="btn-start" href="#">"Start Scroll Prevent"</a>  <a id="btn-stop" href="#">"Stop Scroll Prevent"</a>_x000D_
</p>
_x000D_
_x000D_
_x000D_


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)

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


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

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

}

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

You just need to add in map options:

scrollwheel: false

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').


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.


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to google-maps

GoogleMaps API KEY for testing Google Maps shows "For development purposes only" java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion How to import JSON File into a TypeScript file? Googlemaps API Key for Localhost Getting "Cannot call a class as a function" in my React Project ERROR: Google Maps API error: MissingKeyMapError This page didn't load Google Maps correctly. See the JavaScript console for technical details Google Maps API warning: NoApiKeys ApiNotActivatedMapError for simple html page using google-places-api

Examples related to google-maps-api-3

Google Maps shows "For development purposes only" Googlemaps API Key for Localhost ERROR: Google Maps API error: MissingKeyMapError Google Maps API warning: NoApiKeys Google Maps JavaScript API RefererNotAllowedMapError This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console TypeError: window.initMap is not a function Google maps Marker Label with multiple characters Google Maps how to Show city or an Area outline How to use SVG markers in Google Maps API v3

Examples related to jquery-plugins

How to use a jQuery plugin inside Vue How add spaces between Slick carousel item Bootstrap carousel multiple frames at once Can someone explain how to implement the jQuery File Upload plugin? Correct way to integrate jQuery plugins in AngularJS Call Jquery function Twitter bootstrap remote modal shows same content every time Jquery Chosen plugin - dynamically populate list by Ajax How to show all rows by default in JQuery DataTable Change Placeholder Text using jQuery