update marker location with leaflet API

后端 未结 2 531
说谎
说谎 2021-02-05 00:50

I want to build web app with the Leaflet API. First my user is geolocated with IP then if he accepts I try to update his position with HTML5 geolocation (accuracy is better).

2条回答
  •  迷失自我
    2021-02-05 01:33

    The code inside your question is a little bit confusing, it's hard to say what the issue is when you only post snippets.

    As it is, this code:

        var lat = (e.latlng.lat);
        var lng = (e.latlng.lng);
        var newLatLng = new L.LatLng(lat, lng);
        marker.setLatLng(newLatLng); 
    

    ..should work as expected inside onLocationFound().

    You can simplify it:

    marker.setLatLng(e.latlng);
    

    However, I guess the problem is a scope-issue, some of your variables (e.g. marker) is not accessible inside onLocationFound.

    Here an example how to achieve it:

    function init(){
        var map             = L.map('map', {center: [51.505, -0.09], zoom: 13}),
            marker          = L.marker(map.getCenter()).addTo(map),
            glcl            = google.loader.ClientLocation,
            onLocationfound = function(e){
              marker.setLatLng(e.latlng);
              map.setView(marker.getLatLng(),map.getZoom()); 
              alert('Marker has been set to position :'+marker.getLatLng().toString());
            };
    
        L.tileLayer('http://{s}.tile.cloudmade.com/[yourCloudmadeKey]/997/256/{z}/{x}/{y}.png').addTo(map);
    
        map.on('locationfound', onLocationfound);
    
        if(glcl){//when google.loader.ClientLocation contains result
           onLocationfound({latlng:[glcl.latitude,glcl.longitude]});
        }else{alert('google.loader.ClientLocation fails');}
    
        map.locate();
    } 
    

    Demo: http://jsfiddle.net/doktormolle/6ftGz/

提交回复
热议问题