Using onclick and ontouchstart events in an image

124 Views Asked by At

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);
}
0

There are 0 best solutions below