Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I simply get the current geolocation using leaflet without events?

I've read the leaflet documentation fairly in depth and I can't find a simple answer to my question.

First some context:

I've created a new map and centred it at the current location and added a listener for location found.

    var map = L.map('map', {zoomControl: false}).fitWorld();

    L.tileLayer('https://api.mapbox.com/styles/v1/mapbox/outdoors-v9/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1IjoiZG9ucZhc3o3ODMifQ.3-x6nnTgePEK0ERPllV7oQ', {
        maxZoom: 20
    }).addTo(map);

    map.locate({setView: true, watch: true, maxZoom: 17});
    map.on('locationfound', onLocationFound);

I now want to create a marker at the current location e.g.

    marker = L.marker(map.getLatLong);
    marker.addTo(map);

This is to be done outwith the onLocationFound() function as I want to create it only once and then use the locationfound event to have the marker move using marker.setLatLng().

How am I able to use leaflet to get the current LatLong? Does it have a simple alternative to the HTML5 Geolocation API?

I've tried map.getCenter but it returns (0,0)

like image 383
K. Smith Avatar asked Jan 28 '23 17:01

K. Smith


1 Answers

This is to be done out with the onLocationFound() function as I want to create it only once

In that case, use map.once() instead of map.on(). As you can read in the documentation, once() is the same as on() but only runs on the first event of that kind.

and then use the locationfound event to have the marker move using marker.setLatLng().

In that case, then check if the marker is created, create if it's not, or move it if it is. Something like...

var marker;
map.on('locationfound', function(ev){
    if (!marker) {
        marker = L.marker(ev.latlng);
    } else {
        marker.setLatLng(ev.latlng);
    }
})

I'd also appreciate if anyone knows of a tidy way of doing it without events

In that case, do have a look at the HTML5 geolocation API. There are no events, but there are asynchronous callbacks anyway. You can use those callbacks directly, you can wrap them in event handlers (as Leaflet does), you can wrap them in Promises, but one way or the other you'll have to deal with not-totally-trivial asynchronicity issues.

like image 80
IvanSanchez Avatar answered Jan 31 '23 08:01

IvanSanchez