disable zooming dragging in Google maps by clicking on a button

JavascriptGoogle MapsGoogle Maps-Api-3

Javascript Problem Overview


I want to add codes inside disable() function to disable dragging and zooming in Google maps API v3 by clicking on 'disable' button.

<script type="text/javascript">
   var map;

  function initialize() {
var uluru = new google.maps.LatLng(21, 57);
map = new google.maps.Map(document.getElementById("map"), {
  zoom: 6,
  center: uluru,
  mapTypeId: google.maps.MapTypeId.HYBRID
});
}


function disable(){

}

</script>


<body onload="initialize()" >

   <input type="button" id="next" value="disableZoomDrag" onclick="disable()">

</body>

Javascript Solutions


Solution 1 - Javascript

You can use the setOptions() method on the map object:

map.setOptions({draggable: false, zoomControl: false, scrollwheel: false, disableDoubleClickZoom: true});

If this doesn't prevent zooming, you could always set the minimum and maximum zoom to the current zoom level.

There is also the disableDefaultUI option, which probably takes all of these events into account, but it might disable clicking on existing elements.

Solution 2 - Javascript

@ScottE's answer pointed me in the right direction of using map.setOptions(). However, from the API documentation, I found that there is a more elegant set of options to set. Perhaps these are newer than the answer, but they work pretty well for me.

function disablePanningAndScrolling()
{
    map.setOptions({
        zoomControl: false,
        gestureHandling: 'none'
    });
}

This completely disables zooming and panning.

To return things to normal, just set the properties back to their defaults:

function enablePanningAndScrolling()
{
    map.setOptions({
        zoomControl: true,
        gestureHandling: 'greedy' // or 'cooperative'*
    });
}

*: the default is greedy if the page isn't scrollable, cooperative when it is. Pick whichever was the situation in your application.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSami Al-SubhiView Question on Stackoverflow
Solution 1 - JavascriptScottEView Answer on Stackoverflow
Solution 2 - JavascriptJasperView Answer on Stackoverflow