2015-05-24 116 views
0

我使用OpenLayers從json數據製作地圖。我必須加載它(使用PHP)來檢查時間戳並驗證信息。那時候,我寧願輸出一個javascript變量,只讓OL使用它。我似乎無法在文檔中完成此操作。Openlayers:來自本地變量的矢量圖層

理想情況下,我只希望改變'url': 'latest.json'爲類似'local': json_variable

var pointsSource = new ol.source.GeoJSON({ 
    'projection': map.getView().getProjection(), 
    'url': 'latest.json' 
}); 

var pointsLayer = new ol.layer.Vector({ 
    source: pointsSource, 
    style: new ol.style.Style({ 
     image: new ol.style.Icon(({ 
      anchor: [0.5, 40], 
      anchorXUnits: 'fraction', 
      anchorYUnits: 'pixels', 
      src: 'openlayers/marker-icon.png', 
     })) 
    }) 
}); 
map.addLayer(pointsLayer); 

回答

2

您可以在GeoJSON的數據通過帕拉姆「對象」通過。

OL3 src非常易讀,通常閱讀此文檔可以更快地找出要執行的操作,而不是通過文檔搜索!我假設你使用的是ol3.4或更早的版本;這裏是GeoJSON的3.2 SRC代碼:

https://github.com/openlayers/ol3/blob/v3.2.0/src/ol/source/geojsonsource.js

你可以看到它採用了一個對象PARAM,這是期待一個JS對象,這是JSON.parse("...your geojson string here...")

結果因此,像:

var geojson_cache = "<?php output from PHP here ?>" 
var geojson_object = JSON.parse(geojson_cache) 
var pointsSource = new ol.source.GeoJSON({ 
    'projection': map.getView().getProjection(), 
    object: geojson_object 
}); 

應該做你所需要的。

也僅供參考 - 我提到上述OL3.4或更早版本 - 原因是此類在3.5中不再存在。你可以從上面的src文件中看到,這個類並不比使用格式附加的ol.format.GeoJSON格式化程序的StaticVector包裝更多。這已經過重構,將被ol.source.Vector取代,並提供ol.format.GeoJSON格式化程序。有「新的矢量API」的讀這些注意事項:

https://github.com/openlayers/ol3/releases/tag/v3.5.0

+0

工作就像一個魅力,乾杯! – frogg3862

相關問題