等到所有对象都加载到地图上

时间:2012-10-29 23:36:18

标签: javascript jquery google-maps google-maps-api-3

我正试图在谷歌地图上绘制数百个建筑物的足迹。但是我遇到了回调问题(我认为)......

为此,在加载Google地图后,我从数据库中获取建筑物ID列表,并为每个ID创建一个新的建筑物对象。

主页

function load_buildings() {
    var url='/api/get_imaged_buildings/';
    $.getJSON(url, function(buildings) {
        for(var building in buildings) {
            var new_building = new Building(buildings[building].id, buildings[building].footprint);
        }
    })
    .error(function(jqXhr, textStatus, error) {
        alert("ERROR: " + textStatus + ", " + error);
    });
}

返回:

{"507ca17f0f53664a62000fc0": {"footprint": [[-71.06344334281945, 42.354043084935846], [-71.0637134471212, 42.35412603649889], [-71.06333405397038, 42.35480611690739], [-71.06338439864643, 42.35482782501911], [-71.0632517948924, 42.355064458152995], [-71.063047338961, 42.35496617995809], [-71.06308636758757, 42.35492158377903], [-71.06293828848663, 42.35485043826673], [-71.06289913717758, 42.354895213988364], [-71.06272577376158, 42.35481190819347], [-71.06319845721484, 42.35438624633442], [-71.06344334281945, 42.354043084935846]], "id": "507ca17f0f53664a62000fc0"}, 

Building.js

function Building(id, footprint) {
    this.id = id;
    this.footprint = footprint;
}
Building.prototype.plotFootprint = function() {
    var footprint = [];
    var footprint_from_db = this.footprint;
    for(var i=0; i<footprint_from_db.length; i++)
    {
        var location = footprint_from_db[i];
        var point = new google.maps.LatLng(location[0], location[1]);
        bounds.extend(point);
        footprint.push(point);
    }
    var building = new google.maps.Polyline({
        path: footprint,
        strokeColor: '#e81971',
        strokeOpacity: 1.0,
        strokeWeight: 2
    });
    building.setMap(map);
}

我想要做的是在所有建筑物装满之后绘制所有建筑物。做这个的最好方式是什么?我想优化速度。

感谢。

编辑:我拿出了不好的代码,然后继续运行。现在我想知道如何确定所有脚印何时加载到所有对象中,然后我应该在哪里绘制它们。

1 个答案:

答案 0 :(得分:1)

jQuery有一个叫做Deffered对象的东西 - 它允许你设置一系列回调来按顺序运行,然后在一切都结束后运行一些代码。

查看dox:http://api.jquery.com/category/deferred-object/