Reputation: 571
I'm having a problem with OpenLayers 3.5. I'm trying to use the one-off loading strategy to grab features from a GeoJSON file. I'm adding a new layer to an already instantiated map. My code looks like this:
var vectorSource = new ol.source.Vector({
url: layerInfo.url,
format: new ol.format.GeoJSON()
});
var pointsLayer = new ol.layer.Vector({
source: vectorSource,
style: styleFunc
});
that.map.addLayer(pointsLayer);
pointsLayer.setVisible(true);
However, nothing shows, and when I examine pointsLayer.getSource().getFeatures()
, I discover that no features were actually loaded.
So, now I tried to load the features a different way:
var that = this;
$.get(layerInfo.url, function(response) {
var vectorSource = new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(response)
});
var pointsLayer = new ol.layer.Vector({
source: vectorSource,
style: styleFunc
});
that.map.addLayer(pointsLayer);
pointsLayer.setVisible(true);
});
This DOES work. I'm banging my head against a wall here. Does anyone have any ideas? Thanks so much!
Upvotes: 4
Views: 927
Reputation: 17487
Based on Juan Carlos' answer, and for future reference, here is a function that creates a layer based on GeoJSON, using Angular's $http
service :
function buildStationsLayer() {
var geoJsonUrl = config.stationsGeoDataUrl /*+ some parameters....*/ ;
var source = new ol.source.Vector({});
var format = new ol.format.GeoJSON();
var stationsLayer = new ol.layer.Vector({
source: source,
style: stationStyleFunction //function that styles conditionally depending on resolution
});
//manually load the GeoJSON features into the layer
$http.get(geoJsonUrl).success(function(data){
for(var i=0; i<data.features.length; i++){
var feature = format.readFeature(data.features[i]);
source.addFeature(feature);
}
});
return stationsLayer;
}
Still not happy that the documented way does not work though. I don't understand why because the official example uses the source and format and it works :
var vectorLayer = new ol.layer.Vector({
source: new ol.source.Vector({
url: 'data/geojson/countries.geojson',
format: new ol.format.GeoJSON()
}),
style: function(feature, resolution) {
style.getText().setText(resolution < 5000 ? feature.get('name') : '');
return styles;
}
});
Source : http://openlayers.org/en/master/apidoc/ol.format.WKT.html
It also worked before the change in 3.5, using ol.source.GeoJSON
.
Upvotes: 1
Reputation: 48187
This is how I'm loading the data now, "data" is my GJson
var wktTraffic = new ol.source.Vector({
});
var trafficLayer = new ol.layer.Vector({
source: wktTraffic,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'blue',
width: 5
})
})
});
function showData(data) {
var format = new ol.format.WKT();
var feature;
$.each(data, function (i, link) {
feature = format.readFeature(link.geom);
wktTraffic.addFeature(feature);
})
console.log('done load map');
}
Upvotes: 3