How to make my html website watch my location changes and update it to map? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to make my html website watch my location changes and update it to map?

How do I make my website with leaflet js to constantly watch the location of the user and keep updating the map as he moves? I've been working with leaflet js and I'm stuck trying to make the webmap to continually update the users location as he moves with always prompting... Any help or redirection would be great

2nd Nov 2020, 3:40 PM
kojo Justine
kojo Justine - avatar
2 Answers
+ 5
kojo Justine The Geolocation.watchPosition(...) method is used to register function handlers that will execute when the position changes. The examples in this link should set you straight. https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition
3rd Nov 2020, 12:01 AM
David Carroll
David Carroll - avatar
+ 4
It sounds like you want access to a smart phones GPS sensor. JavaScript's standard geolocation API will get the current location if the website visitor grants permission. https://www.w3schools.com/html/html5_geolocation.asp You could write JavaScript to run on a set interval like every few seconds to see if the location changed and update the leaflet map accordingly. Something like this would set the center of the leaflet map to some arbitrary coordinates: map.panTo(new L.LatLng(40.737, -73.923)); Here is a more complete example: // Assumes map refers to your leaflet map. function updateLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { console.log("Geolocation is not supported by this browser."); } } function showPosition(position) { map.panTo(new L.LatLng(position.coords.latitude, position.coords.longitude)); } // updateLocation every 5 seconds. setInterval(updateLocation, 5000); Keep in mind that laptops and some tablets don't have GPS sensors and getting a location can be very inaccurate off IP address.
2nd Nov 2020, 10:03 PM
Josh Greig
Josh Greig - avatar