Integrating Gesture Handling in Leaflet JS for two-finger scrolling enforcement

Have you ever noticed that when you're using a mobile device and scrolling down a webpage with a Google map, the map goes dark and prompts you to "Use two fingers to move the map"? https://i.stack.imgur.com/4HD1M.jpg

I am interested in incorporating this feature into my Leaflet map. Unfortunately, Leaflet does not currently offer this functionality out of the box.

Google calls this feature Gesture Handling. By setting it to "Cooperative," you can achieve the effect I mentioned earlier. https://developers.google.com/maps/documentation/javascript/interaction

Detecting the number of fingers being used and displaying the message, as shown in my code example, is relatively straightforward. (To see it in action, you will need to run this on a mobile device or emulator)

If only one finger is detected, I disable the touchmove event and display a warning. If multiple fingers are detected, the event is allowed to apply to the map. However, I am looking for a way to transfer that single-fingered touch event to the parent document after canceling it on the map so that the user can scroll the page instead.

Do you have any good ideas on how to accomplish this? I considered using dispatchEvent to relay the received touchmove event object directly to the parent document. For example: document.dispatchEvent(touchmoveevent); But unfortunately, that did not work. Maybe there's a better overall approach.

var myMap = L.map('mapid').setView([51.505, -0.09], 13);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  maxZoom: 19
}).addTo(myMap);

$("#mapid").on("touchmove", function(e) {
  if (e.touches.length !== 2) {
    $('.mask').fadeIn();
    return false;
  }
});

$("#mapid").on("touchend", function(e) {
  if ($('.mask').is(':visible')) {
    $('.mask').fadeOut();
  }
});
#mapid {
  height: 600px;
}

.mask {
  display: none;
  position: absolute;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  top: 0;
  left: 0;
  z-index: 400;
}

.message {
  color: #ffffff;
  position: absolute;
  width: 100%;
  text-align: center;
  top: 50%;
  transform: translateY(-50%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9a5aca8afa5acbd89f8e7fae7f8">[email protected]</a>/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin="" />
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="93fff6f2f5fff6e7d3a2bda0bda2">[email protected]</a>/dist/leaflet.js" integrity="sha512-/Nsx9X4HebavoBvEBuyp3I7od5tA0UzAxs+j83KgC8PU0kgB4XiK4Lfe4y4cgBtaRJQEIFCW+oC506aPT2L1zw==" crossorigin=""></script>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">

  <head>

    <body>
      <h1>Leaflet Map</h1>

      <div id="mapid"></div>
      <div class="scroll-shield"></div>
      <div class="mask">
        <div class="message">
          <p>Use two fingers to move the map</p>
        </div>
      </div>

      <h2>Stuff below</h2>
      <ul>
        <li>Here</li>
        <li>is</li>
        <li>some</li>
        <li>stuff</li>
        <li>below</li>
      </ul>

    </body>

Answer №1

The key to success in this situation was making sure that dragging, tap, and scrollWheelZoom were disabled when initializing the map.

Afterwards, I temporarily re-enabled them when two-fingered dragging or scrolling with the command or ctrl key was detected.

Now, I have integrated this solution into a custom leaflet plugin.

Visit my GitHub repository for more information.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Experiencing ERR_TOO_MANY_REDIRECTS while using Next.js with Vercel and a Custom Domain through Cloudflare

I'm having trouble getting my Next.js project set up on Vercel with a custom domain managed through Cloudflare. Despite configuring the DNS and SSL settings correctly, I keep seeing a net::ERR_TOO_MANY_REDIRECTS error when trying to access my site at ...

Make sure to execute a function prior to the ajax beforeSend

Before I upload a file using 'fileuploader', I attempted to check the file first in my beforeSend function: beforeSend: function(item, listEl, parentEl, newInputEl, inputEl) { var file = item.file; let readfile = functio ...

Trigger a click event to alter the child div elements

I have a <div> that expands when clicked and shrinks back when clicked again. Inside this div are images that should only appear once the div expands. My issue is ensuring that all images except the first one are hidden until the div expands. https: ...

The ajax method for loading an xml file results in displaying the undefined message

When attempting to fetch content from an xml file using ajax, the page initially displays "undefined". However, upon refreshing the page, the content loads successfully. Take a look at my code snippet below: $.ajax({ type: "GET", url: "xm ...

What is the best way to retrieve both the start and end date values from a React date range picker component

I have integrated a date range picker npm package called react-date-range into my code. On my screen, there is an "Apply Dates" button. When this button is clicked, I want to retrieve the selected date range value. How can I achieve this onclick event? ...

Ensure the button remains in focus after clicking on the input field: Material-Ui

I'm currently working with a material-ui dialog and I've encountered an issue. When I click on the input field, the social button loses focus which is not what I want. Here's how it looks: Here's the desired behavior where the social b ...

Switch Tabs with Dropdown Selection

I came across a website with a similar feature, but I am interested in using a dropdown menu instead of a button or link. Check out this webpage for reference The problem seems to be related to this line of code: onchange="$('#'+$this).tri ...

"415 (Unsupported Media Type) encountered when making a POST request in a REST API

I've encountered an issue with a React component where a checkbox triggers a POST request to a REST API with a single parameter. Despite setting a breakpoint in the WebAPI code, it's not being hit and I'm receiving a 415 Unsupported Media Ty ...

Performing Batch Writes in Firestore using the Admin SDK

I have a massive ASCII flat file containing 1.5 million lines, which is essentially a list of parts from a manufacturer. I want to store this data in Firestore. Originally saved as a .csv file, the size was 250GB. After converting it to a JSON file using ...

input value does not change when the "keyup" event is triggered

I'm encountering an issue with the code below. The code is for a simple To Do app using Javascript. I followed a tutorial step by step, but my app isn't functioning as expected. When I press the enter key, the input value should be added to the l ...

'this' in Arrow functions does not have a reference to the calling context

Something seems off about the context in this code. I've left comments to describe my issue below: const cat = { //arrow function meow: () => { console.log(this); }, makeMeow(){ // Why does 'this' refer ...

What is the best way to transfer an argument from a parsed JSON value to an onclick function?

In our dataset, we have a specific table that contains valuable information. My main objective is to transfer an argument extracted from parsed JSON data to a separate JavaScript function known as newStory(value['stories']) using the onclick meth ...

In my Node.js/Express.js application, I have a directory that holds various images. Whenever I attempt to view these images via their URL, I encounter a 404 error message

In my Node.js/Express js project, I have the following folder structure: root ----bin ----controllers ----middleware ----models ----node_modules ----public --------images ------------test.png ----routes ----views I am currently trying to determine the cor ...

Load Angular modules dynamically

Is there a way to dynamically load a module (js, css and html) using a single directive at any point during the app's lifecycle? <my-module id="contacts"></my-module> The template for this directive looks like this <my-module id="con ...

ajax: ensure utf-8 encoding is applied

I am facing an issue with my webpage that is saved in UTF-8 encoding. In the head section of the HTML document, I have defined it as follows: <meta charset="utf-8" /> Within an external JavaScript file, there is a function called ajax_db() which ma ...

Ensuring a fixed table with vertical scrolling only, no horizontal scrolling, while scrolling in either direction

I'm working with an HTML fixed design that contains a center-aligned table with extensive data scrollable both vertically and horizontally. To address the issue of keeping column headers visible when scrolling vertically, I used jQuery's clone() ...

React Weather App: difficulties entering specific latitude and longitude for API requests

I have successfully developed an app that displays the eight-day weather forecast for Los Angeles. My next objective is to modify the longitude and latitude in the API request. To achieve this, I added two input fields where users can enter long/lat values ...

Is there a way to customize the color of an element within CardHeader in MUI?

Is there a way to customize the colors of {note.title} and {note.category}? I have attempted to do so by creating a theme: const theme = createTheme ({ palette: { category: { color: blue } } }) Unfortunately, this appro ...

Is it possible to generate a JSON file from a flowchart with the help of d3.js?

Situation: I'm currently in the process of developing a tool that will enable us to generate flow charts and then export the data into a JSON file for use in other services. Being new to JavaScript, I've come across d3 quite often. Can d3 handle ...

Reverse the color of H1 text within a vertical div

Is it feasible to reverse the coloring of a segment within an h1 element using a div, horizontally? Refer to the illustration shown in the image below. https://i.sstatic.net/QAKwD.jpg ...