宣传单地图不符合标准

时间:2017-01-09 05:56:30

标签: javascript leaflet

我试图将地图拟合到2D数组定义的边界。即使标记已添加到地图中并且是有效的坐标,我仍然会收到错误Error: Bounds are not valid. leaflet.js:5:21909

var map = L.map('map', { zoomControl:false });
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="http://openstreetmap.org/copyright">OpenStreetMap contributors</a>'
}).addTo(map);



map.setView([0, 0], 2);

var markers = new L.FeatureGroup();
map.addLayer(markers);


function drawResults(){
    // get offer keys
    var offers = new Array();
    var articles = [];


    offersRef.once("value", function(snapshot) {        
        var offerKeys = Object.keys(snapshot.val());
        for (var i=0; i<offerKeys.length; i++){
            var offer = snapshot.val()[offerKeys[i]];           
            var lat = offer.lat;                
            var lng = offer.lng;
            console.log(lat);// outputs 33.2321
            console.log(lng);// outputs 101.1234
            offers.push([lat, lng]);
            var marker = L.marker([lat, lng]).addTo(markers);
        }

    });
    map.fitBounds(markers.getBounds());

    }
    console.log(offers);    

}

drawResults();

任何人都可以看到我做错了吗?

编辑: 控制台日志

35.0721909  app.js:350:13
-106.48798399999998  app.js:351:13
35.0526641  app.js:350:13
-78.87835849999999  app.js:351:13

1 个答案:

答案 0 :(得分:2)

您需要将调用转移到map.fitBounds进入回调,因为once方法(看起来像Firebase API调用)可能是异步的:

offersRef.once("value", function(snapshot) {
    var offerKeys = Object.keys(snapshot.val());
    for (var i = 0; i < offerKeys.length; i++) {
        var offer = snapshot.val()[offerKeys[i]];
        var lat = offer.lat;
        var lng = offer.lng;
        offers.push([lat, lng]);
        var marker = L.marker([lat, lng]).addTo(markers);
    }
    map.fitBounds(markers.getBounds());
});

如果在回调之外调用它,则在功能组中不会有任何标记,并且组的界限不会有效。