Paul
Paul

Reputation: 105

OpenLayers features array is empty

I've got a map that displays a KML Vector layer with some markers. When you click on the marker it pops up an info box. I want to be able to automatically pop up an info box based on a parameter passed into the page. I think I need to do this by using getFeaturesByAttribute() to find a name, however the features array always seems to be empty. (Though I can see the contents when I use FireBug)

What do I need to do to get items in the array?

Code:

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

    }

Upvotes: 3

Views: 2803

Answers (1)

AlexC
AlexC

Reputation: 10756

This issue, I think, is because the HTTP call is happening asynchronously to populate the features of the layer. You are therefore hitting alert(groups.features.length) before the HTTP call has returned and hence the layer has no features so groups.features.length is rightly 0. If you want to see the number of features in this manner you need to attach function to the layer loadend event which will call after the HTTP event has returned and you will be able to interrogate all the features.

Upvotes: 2

Related Questions