Leaflet: How to handle touch events (e.g. on mobile devices)

Viewed 1725

Please take a look at the code below. It's drawing a circle onto the map. If the user clicks with the mouse or taps with his finger (on a mobile device) into the circle and drags it, the circle should be moved across the map.

This works for Desktop Firefox, Desktop Chrome, Mobile Firefox. But not with Mobile Chrome. I think that the code in Mobile Firefox maybe just works because the browser emulates touch-inputs to mouse-inputs which of course are working well in Leaflet.

So I need help how to best implement touch events (parallel to mouse events) within Leaflet. Touch events are not mentioned in Leaflet's Doc. But i think the usual Javascript DOM-events should work too? (touchstart, touchmove, touchend). But not within Chrome mobile the way my code is written.

<!DOCTYPE html>
<html>
<head>
 <title>Eventtest</title>
 <meta charset="utf-8" />
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.1.0/dist/leaflet.css"/>
    <script src="https://unpkg.com/leaflet@1.1.0/dist/leaflet.js"></script>
</head>
<body>
<div id="mapid" style="width: 600px; height: 400px;"></div>
<script>
var mymap = L.map('mapid').setView([51.505, -0.09], 13);
 L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
  maxZoom: 18,
  attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
   '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
   'Imagery © <a href="http://mapbox.com">Mapbox</a>',
  id: 'mapbox.streets'
 }).addTo(mymap);

 circle = L.circle([51.508, -0.11], 500, {
  color: 'red',
  fillColor: '#f03',
  fillOpacity: 0.5
 }).addTo(mymap);

 circle.on('mousedown touchstart', onCircleDown);
 
 function onCircleDown (e1) {
  mymap.dragging.disable();
  var mouseStartingLat = e1.latlng.lat;
  var mouseStartingLng = e1.latlng.lng;
  var circleStartingLat = e1.target._latlng.lat;
  var circleStartingLng = e1.target._latlng.lng;
  circle.on('mousemove', function (e2) {
    var mouseNewLat = e2.latlng.lat;
                var mouseNewLng = e2.latlng.lng;
                var latDifference = mouseNewLat - mouseStartingLat;
                var lngDifference = mouseNewLng - mouseStartingLng;
                var currentCircleCoords = L.latLng (circleStartingLat + latDifference, circleStartingLng + lngDifference);
                e1.target.setLatLng (currentCircleCoords);
  });
  circle.on ('mouseup', function () { 
                    circle.off('mousemove');
     mymap.dragging.enable();
                });
 }

</script>
</body>
</html>

0 Answers
Related