2012-04-16 92 views
3

我有一張地圖,顯示帶有某些標記的KML矢量圖層。當你點擊標記時,它彈出一個信息框。我希望能夠根據傳入頁面的參數自動彈出一個信息框。 我想我需要通過使用getFeaturesByAttribute()來查找名稱,但features數組似乎總是空的。 (雖然我能看到的內容,當我使用Firebug)OpenLayers功能陣列爲空

什麼我需要做的就是數組中的項?

代碼:

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 

    } 

回答

2

這個問題,我想,是因爲HTTP調用異步發生填充層的功能。因此,您在HTTP調用返回之前觸擊了alert(groups.features.length),因此該圖層沒有任何特徵,因此groups.features.length正確地爲0.如果要以這種方式查看特徵的數量,您需要附加功能到layer loadend event,在HTTP事件返回後將調用,您將能夠詢問所有功能。

+0

謝謝,工作出色! – Paul 2012-04-18 08:09:59