Search code examples
leaflet

Leaflet.js: Use ctrl + scroll to zoom the map & Move map with two fingers on mobile


I'm using http://leafletjs.com/ ... is it possible to only:

  1. Use ctrl + scroll to zoom the map

  2. Move map with two fingers on mobile/tablet

... so similar what google maps does? With the comments ...

So far thats my setup:

// Leaflet Maps
var contactmap = L.map('contact-map', {
        center: [41.3947688, 2.0787279], 
        zoom: 15,
        scrollWheelZoom: false
    });

Solution

  • There is an amazing library that does exactly that. Leaflet.GestureHandling

    It is an add on to leaflet that works right of the box, it's also modular and can be installed using npm.

    Here's a working example using leaflet and GestureHandling. You can try it also on mobile.

    P.S. It has multiple languages baked in:)

    // Attach it as a handler to the map
    
    const map = L.map('map', {
      gestureHandling: true
    }).setView([51.505, -0.09], 13);
    
    // Add tile layer
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);
        #map {
          height: 400px;
          width: 400px;
        }
      <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
            integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA=="
            crossorigin=""/>
      <link rel="stylesheet" href="//unpkg.com/leaflet-gesture-handling/dist/leaflet-gesture-handling.min.css"
            type="text/css">
      <script src="https://unpkg.com/[email protected]/dist/leaflet.js"
              integrity="sha512-QVftwZFqvtRNi0ZyCtsznlKSWOStnDORoefr1enyq5mVL4tmKB3S/EnC3rRJcxCPavG10IcrVGSmPh6Qw5lwrg=="
              crossorigin=""></script>
      <script src="//unpkg.com/leaflet-gesture-handling"></script>
      
      
      
      <div id="map"></div>