Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to locate user with leaflet locate?

I'm trying to locate a user and set the map to this position with leaflet:

    <script>
    var map;

    function initMap(){
        map = new L.Map('map',{zoomControl : false});
        var osmUrl = 'http://{s}.tile.openstreetmap.org/mapnik_tiles/{z}/{x}/{y}.png',
            osmAttribution = 'Map data &copy; 2012 OpenStreetMap contributors',
            osm = new L.TileLayer(osmUrl, {maxZoom: 18, attribution: osmAttribution});
        map.setView(new L.LatLng(51.930156,7.189230), 7).addLayer(osm);
    }

    function locateUser(){
        map.locate({setView : true});
    }
</script>

On execute the browser ask for permission, but then nothing happens? What's wrong with my code?

like image 866
fillibuster Avatar asked May 12 '12 12:05

fillibuster


1 Answers

Here is a quick hack. I recommend this plugin https://github.com/domoritz/leaflet-locatecontrol

var loadMap = function (id) {
    var HELSINKI = [60.1708, 24.9375];
    var map = L.map(id);
    var tile_url = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png';
    var layer = L.tileLayer(tile_url, {
        attribution: 'OSM'
    });
    map.addLayer(layer);
    map.setView(HELSINKI, 19);

    map.locate({setView: true, watch: true}) /* This will return map so you can do chaining */
        .on('locationfound', function(e){
            var marker = L.marker([e.latitude, e.longitude]).bindPopup('Your are here :)');
            var circle = L.circle([e.latitude, e.longitude], e.accuracy/2, {
                weight: 1,
                color: 'blue',
                fillColor: '#cacaca',
                fillOpacity: 0.2
            });
            map.addLayer(marker);
            map.addLayer(circle);
        })
       .on('locationerror', function(e){
            console.log(e);
            alert("Location access denied.");
        });
};

loadMap('map');
like image 91
Abel Terefe Avatar answered Oct 18 '22 01:10

Abel Terefe