0

I have been working on geolocation of a user in leaflet map and I'm loving the experience with leaflet. Everything works except when the same map is viewed on a mobile phone, the "getPosition" function does not work when the image is touched on screen. Can anyone identify the problem or how I should go about it. The "onclick" function works with the goelocation function but "ontouchstart" does not. I have tested "ontouchstart" using "alert(test);" and it works but when using the geolocation function it does not. Here is the code: HTML

<div id="image">
  <img src="location.png">    
</div> 

JavaScript code for map

var map_init = L.map('map');

JavaScript code for Geolocation function

function getPosition(position) {
  console.log(position)
  lat = position.coords.latitude;
  long = position.coords.longitude;
  accuracy = position.coords.accuracy;

  if (marker) {
     map_init.removeLayer(marker);
  }

  if (circle) {
     map_init.removeLayer(circle);
   }

   marker = L.marker([lat, long]);
   circle = L.circle([lat, long], { radius: accuracy });

   //.featureGroup creates a Leaflet Feature Group that adds its child layers into a parent group when added to a map
   var featureGroup = L.featureGroup([marker, circle]).addTo(map_init);

   map_init.fitBounds(featureGroup.getBounds());

   console.log("Your coordinate is: Lat: " +lat +" Long: " +long +" Accuracy: " +accuracy);        
        };

JavaScript code for "onclick" and "ontouchstart"

var image = document.getElementById('image');
image.onclick = function() {
  navigator.geolocation.getCurrentPosition(getPosition);
}
image.ontouchstart =function() {
  navigator.geolocation.getCurrentPosition(getPosition);
}
Madea
  • 25
  • 4
  • You might look at using the pointerDown event which works with both desktop and mobile. See: [MDN Pointer Events](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events) – Yogi Jun 29 '22 at 12:12
  • Hello, @Yogi, I have tried it but on the phone still nothing happens when the image is touched. Thanks. – Madea Jun 29 '22 at 12:32
  • Voted to close. I tested your code, but was not able to duplicate the described problem. The image click and touch events fire on mobile and the geolocation data is reported. All works as expected. The problem might be that geolocation permissions are not enabled on the test device. Adding an error handler to getCurrentPosition or checking dev console output might provide more information. – Yogi Jun 29 '22 at 16:17
  • Hello @Yogi, I have tested the map on different mobile devices but even when I use setInterval() command to automatically show my current location after some seconds, nothing happens on the phones but it works fine on the desktop – Madea Jun 30 '22 at 08:51

0 Answers0