Reputation: 346
If you want to import a json file in your system to a vector layer, is as easy as:
var restaurantsold = new ol.layer.Vector({
title: 'b_layer',
source: new ol.source.Vector({
url: 'restaurantjson.geojson',
format: new ol.format.GeoJSON()
}),
});
And I can add that layer directly to the map. But if I try to make a call to an API, I can't display it in the map, my best try has been this:
var restaurants;
$.ajax({
type: "GET",
url: "http://tour-pedia.org/api/getPlaces?category=restaurant&location=Berlin&name=La+Dolce+Vita",
dataType:"json",
success:function(data){
console.log(data)
restaurants = data;
$(restaurants).each(function(index, value) {
console.log(value.address);
});
}
});
var resta2 = new ol.layer.Vector({
title : "Resta2",
source: new ol.source.Vector(restaurants)
});
And I can't find a proper solution anywhere for this, thanks for your help!
EDIT: at the end the problem was that it gets a JSON file, and openlayers wants an GeoJSON file.. my way to solve it was to convert it to GeoJSON following this: https://gis.stackexchange.com/questions/73756/is-it-possible-to-convert-regular-json-to-geojson
Upvotes: 0
Views: 2763
Reputation: 1159
The Restaurant data might not be available at all when you are creating the vector layer since you are making an Ajax Call.
So convert the GeoJSON to collection of ol.Feature
objects using ol.format.GeoJSON
readFeatures()
method. Then add it vector source using addFeatures()
method.
Fix :
var vectorSource = new ol.source.Vector({
format: new ol.format.GeoJSON()
})
var restaurantsold = new ol.layer.Vector({
title: 'b_layer',
source : vectorSource
});
$.ajax({
type: "GET",
url: "http://tour-pedia.org/api/getPlaces?category=restaurant&location=Berlin&name=La+Dolce+Vita",
dataType:"json",
success:function(data){
// If response is valid
var geojsonFormat = new ol.format.GeoJSON();
// reads and converts GeoJSon to Feature Object
var features = geojsonFormat.readFeatures(data);
vectorSource.addFeatures(features);
}
});
Upvotes: 3