简体   繁体   English

传单地图不适合边界

[英]Leaflet map won't fit bounds

I'm trying to fit a map to bounds defined by a 2D array.我正在尝试将地图拟合到由 2D 数组定义的边界。 I keep getting the error Error: Bounds are not valid. leaflet.js:5:21909我不断收到错误Error: Bounds are not valid. leaflet.js:5:21909 Error: Bounds are not valid. leaflet.js:5:21909 even though the markers are added to the map and are valid coords.即使标记已添加到地图并且是有效坐标, 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();

Can anyone see what I'm doing wrong?谁能看到我做错了什么?

Edit: Console logs编辑:控制台日志

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

You will need to move the call to map.fitBounds into the callback, as the once method (which looks like a Firebase API call) is likely asynchronous:您需要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());
});

If it's called outside the callback, there won't be any markers in the feature group and the group's bounds won't be valid.如果在回调之外调用,则要素组中将没有任何标记,并且该组的边界将无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM