Search code examples
javascriptgoogle-mapsbrowserzoomingpinchzoom

How to prevent native browser default pinch to zoom behavior?


This question has been asked in a couple different flavors, but none satisfy.

The native browser (Google Chrome for Mac, for instance) supports the "pinch to zoom" gesture by default which will zoom the whole viewport. How do I disable (react to) this default behavior so I can write my own pinching/zooming logic? Google Maps https://maps.google.com/ seems to have achieved this since pinching on the map will only scale the map area, leaving the rest of the UI intact, while pinching on the left sidebar shows the default behavior.

I have tried a few approaches such as HTML "viewport" meta tag, CSS touch-action: none; and JavaScript document.addEventListener('touchmove', e => { e.preventDefault() }), but they all seem to only work on mobile.


Solution

  • I accidentally found a solution which works on Chrome. You basically have to preventDefault the "wheel" event. ctrlKey will be true if it is a pinch event instead of a scroll.

    element.addEventListener('wheel', event => {
       const { ctrlKey } = event
       if (ctrlKey) {
          event.preventDefault();
          return
       }
    }, { passive: false })
    

    I'd guess this is how Google Maps does it.

    The (most) cross-browser solution is probably a combination of the techniques mentioned: user-scalable=no in the "viewport" meta tag for the browsers that do support it and this one for native Chrome.