OpenLayers功能数组为空

时间:2012-04-16 08:59:54

标签: openlayers

我有一张地图,显示带有一些标记的KML Vector图层。当您单击标记时,它会弹出一个信息框。我希望能够根据传递到页面的参数自动弹出一个信息框。 我想我需要通过使用getFeaturesByAttribute()来查找名称,但是features数组似乎总是为空。 (虽然我在使用FireBug时可以看到内容)

在数组中获取项目需要做什么?

代码:

function init()
{
        var options = {
            projection: new OpenLayers.Projection("EPSG:900913"),
            displayProjection: new OpenLayers.Projection("EPSG:4326"),
            units: "m",
        };
        map = new OpenLayers.Map('map', options);
        var mapnik = new OpenLayers.Layer.OSM("OpenStreetMap");
        var gmap = new OpenLayers.Layer.Google("Google", {sphericalMercator:true});
        var gsat = new OpenLayers.Layer.Google(
            "Google Satellite",
            {type: google.maps.MapTypeId.SATELLITE, numZoomLevels: 22}
        );

        groups = new OpenLayers.Layer.Vector("Groups", {
            projection: map.displayProjection,
            strategies: [new OpenLayers.Strategy.Fixed()],
            protocol: new OpenLayers.Protocol.HTTP({
                url: "http://maps.google.co.uk/maps/ms?msa=0&msid=210450558816094618535.0004bd79ceb30e9acb9da&output=kml",
                format: new OpenLayers.Format.KML({
                    extractStyles: true,
                    extractAttributes: true
                })
            })
        });

        map.addLayers([mapnik, gmap, gsat, groups]);

        select = new OpenLayers.Control.SelectFeature(groups);

        groups.events.on({
            "featureselected": onFeatureSelect,
            "featureunselected": onFeatureUnselect
        });

        map.addControl(select);
        select.activate();   

        map.addControl(new OpenLayers.Control.LayerSwitcher());

        var center = new OpenLayers.LonLat(-2.58789,51.52283).transform(map.displayProjection, map.projection);
        var zoom = 12
        map.setCenter(center, zoom);

        alert(groups.features.length);   // is always 0

    }

1 个答案:

答案 0 :(得分:2)

我认为这个问题是因为HTTP调用异步发生以填充图层的功能。因此,在HTTP调用返回之前,您正在发出警报(groups.features.length),因此该层没有任何功能,因此groups.features.length正确为0.如果要以这种方式查看功能的数量,则需要将函数附加到layer loadend event,它将在HTTP事件返回后调用,您将能够查询所有功能。