Javascript 如何使用传单定位定位用户?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10563789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:53:48  来源:igfitidea点击:

How to locate user with leaflet locate?

javascriptleaflet

提问by fillibuster

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?

执行时浏览器请求许可,但没有任何反应?我的代码有什么问题?

采纳答案by ScottB

You have an issue with the scope of your map variable. I have posted an example that fixes your code here: http://jsfiddle.net/XwbsU/3/

您的地图变量的范围有问题。我在这里发布了一个修复您的代码的示例:http: //jsfiddle.net/XwbsU/3/

You should receive the browser geolocation popup when you click 'Find me!'.

当您单击“查找我!”时,您应该会收到浏览器地理定位弹出窗口。

Hopefully that helps you.

希望这对你有帮助。

回答by Abel Terefe

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

这是一个快速的技巧。我推荐这个插件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');