For simplicty, referencing this example:
https://carto.com/developers/carto-vl/examples/#example-load-external-geojson-layer
I would like to have this bit of code behave the same as through it were an in-line GeoJSON declaration
fetch('https://libs.cartocdn.com/carto-vl/assets/stations.geojson')
.then(response => response.json())
.then(function(data){
// Define layer
const source = new carto.source.GeoJSON(data);
const viz = new carto.Viz();
const layer = new carto.Layer('layer', source, viz);
layer.addTo(map, 'watername_ocean');
layer.on('loaded', hideLoader);
});
For example (this code works, although for brevity only includes one coordinate):
const stations =
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"name": "Van Dorn Street",
"marker-color": "#0000ff",
"marker-symbol": "rail-metro",
"line": "blue"
},
"geometry": {
"type": "Point",
"coordinates": [
-77.12911152370515,
38.79930767201779
]
}
},
]
};
const source = new carto.source.GeoJSON(stations);
const viz = new carto.Viz();
const layer = new carto.Layer('layer', source, viz);
layer.addTo(map, 'watername_ocean');
The above is an in-line example which avoids issues relating to global variables versus a variable defined within a function.
What I'm trying to figure out to no avail is how to do use fetch to define a global variable, with the same ease as defining it in-line.
This code does not work:
let stations;
fetch('https://libs.cartocdn.com/carto-vl/assets/stations.geojson').then(
function(u){ return u.json();}
).then(
function(json){
stations = json;
}
)
const source = new carto.source.GeoJSON(stations);
const viz = new carto.Viz();
const layer = new carto.Layer('layer', source, viz);
layer.addTo(map, 'watername_ocean');
Generates the following errors:
Error: [Missing required property] 'data' carto-vl.min.js:6:3429