Openlayers: Vector Layer from Local Variable

时间:2015-05-24 20:34:42

标签: javascript json openlayers

I am using OpenLayers to make a map from json data. I have to load it once already (with PHP) to check timestamps and verify information. At that point, I'd rather output a javascript variable and just have OL use that. I can't seem anything in the docs to accomplish this.

Ideally, I'd just change 'url': 'latest.json' to something like '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);

1 个答案:

答案 0 :(得分:2)

You can pass in your geojson data via the param 'object'.

The OL3 src is quite readable and often it is faster to read this to work out what to do than it is to hunt through the docs! I'm assuming you're using ol3.4 or earlier; here is the 3.2 src code for geojson:

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

You can see it takes an object param, which is expecting a JS object, which is the result of JSON.parse("...your geojson string here...")

So something like:

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
});

should do what you need.

Also FYI -- I mention OL3.4 or earlier above - the reason is that this class no longer exists in 3.5. You can see from that src file above that this class isn't much more than a wrapper around StaticVector with a ol.format.GeoJSON formatter attached. This has been refactored and will be replaced by ol.source.Vector and you provide the ol.format.GeoJSON formatter. Have a read of 'New Vector API' in these notes:

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