I have a ASP.NET MVC web application that creates some GeoJSON files depending on client input and saves these files on a published folder on server. These files are to be vector data sources for an OpenLayers map on client side. I use a loop for this purpose to populate a JavaScript array and give this array to map object :
for (let i = 0; i < dataSources.length; i++) {
var ds = new ol.source.Vector({ format: new ol.format.GeoJSON(), url: dataSources[i], });
var st = new ol.style.Style({ stroke: new ol.style.Stroke({ color: '#FF8000', width: 2, }) });
var ly = new ol.layer.Vector({ source: ds, style: st });
layerArray.push(ly);
}
var map = new ol.Map({
target: 'map',
layers: layerArray,
view: new ol.View({ center: ol.proj.fromLonLat([@Html.ViewBag.CenterX,
@Html.ViewBag.CenterY]),zoom: @Html.ViewBag.MapZoom})
});
dataSources array contains GeoJSon file names for example :
'../../Content/dd47c229.json'
'../../Content/ea977438.json'
.....
.....
I only have the first file displayed on the map and when I inspect the page I can see this error:
Uncaught SyntaxError: Unexpected token { in JSON at position 9724
at JSON.parse (<anonymous>)
at n_ (JSONFeature.js:202:25)
at n.readFeatures (JSONFeature.js:55:7)
at XMLHttpRequest.a.onload (featureloader.js:106:20)
the position of this error is always the length of the first file in dataSources array (here : dd47c229.json). It seems that ol.source.Vector constructor does not read the second file from position 0, seems it is not a new Vector object and still has previous JSON code from the first file in memory. Is it true? Any solution for this problem?
More info:to get sure that files are valid and there is no problem with files,I made a map with 3 layers,an OSM tile layer and 2 vector layers that their data sources were 2 same files as I mentioned above and it worked. So I got sure that files are valid.The code for this part is here and I commented it in my view :
//var ds1 = new ol.source.Vector({ format: new ol.format.GeoJSON(), url: '../../Content/d3.json', });
//var st1 = new ol.style.Style({ stroke: new ol.style.Stroke({ color: '#FF8000', width: 2, }) });
//var ly1 = new ol.layer.Vector({ source: ds1, style: st1 });
//layerArray.push(ly1);
//var ds2 = new ol.source.Vector({ format: new ol.format.GeoJSON(), url: '../../Content/d4.json', });
//var st2 = new ol.style.Style({ stroke: new ol.style.Stroke({ color: '#FF8000', width: 2, }) });
//var ly2 = new ol.layer.Vector({ source: ds2, style: st2 });
//layerArray.push(ly2);
as you can see I used different variables out of a loop for each layers and it worked properly , so I got suspected maybe there is something wrong inside the loop.I assume that in each loop iteration variables ds,st and ly become new javascript objects so ds=new ol.source.Vector gets initialized with new parameters . Is it true?