11

ユーザーを見つけて、リーフレットを使用してマップをこの位置に設定しようとしています:

    <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>

ブラウザの実行時に許可を求めますが、何も起こりませんか? コードの何が問題になっていますか?

4

3 に答える 3

16

これが簡単なハックです。このプラグインをお勧めします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');
于 2013-08-13T12:39:08.100 に答える
8

マップ変数のスコープに問題があります。ここにコードを修正する例を投稿しました: http://jsfiddle.net/XwbsU/3/

「Find me!」をクリックすると、ブラウザーの地理位置情報のポップアップが表示されます。

うまくいけば、それはあなたを助けます。

于 2012-05-18T13:05:37.903 に答える