I want to add a button to my leaflet that zooms to the position of the user. I can't figure out the right way. This is what I tried:

L.easyButton('<img src="myimage.png">', function(btn, map){
  map.locate({setView: true, maxZoom: 18});

var Test = L.popup().setContent("Your Location");

this does not work...


Your code for adding an Easy Button and have the map locate the user looks to be working. In the sense that it correctly requests the user his/her permission to use the geolocation API.

It also correctly sets the view to that position once the location completes.

So I assume what you may ask for is how to get the popup set on that position once the location completes, as the code you provide seems not working for that very part?

In that case, you would simply have to bind a callback on map locationfound event, as explained in the map locate method.

// Use map event 'locationfound' to perform some operations once
// the browser locates the user.
map.on('locationfound', function (event) {
    L.circle(event.latlng, event.accuracy).addTo(map);
    var Test = L.popup().
        setContent("Your Location").

Demo: http://jsfiddle.net/ve2huzxw/67/

  • when i clicked my button i was able to give permission to locate my location but in most cases nothing happened. somehow it showed my correct location when i refreshed firefox. with ur code i really got what i wanted. only one problem: it always gives me the wrong location. how can i solve this problem? – howard.D Nov 28 '15 at 20:39
  • It is hard to help with so few details. Would you be able to reproduce your issue online? Do you have a wrong location with the jsfiddle provided in the above answer? Are you using a landline Internet connection, public WiFi, mobile device? – ghybs Nov 29 '15 at 3:32
  • with ur jfiddle provided in the above answer i dont get my correct location. same problem with my leaflet. im unsing a landline internet connection. – howard.D Nov 29 '15 at 11:25
  • ok i testet it once again and i got my correct location. then i did it one more time and got the wrong location again... – howard.D Nov 29 '15 at 11:30
  • Unfortunately this sounds to be related to inherent accuracy of the Geolocation API. See andygup.net/… to get some details. – ghybs Nov 29 '15 at 12:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.