I have defined variable fc
before a getJSON()
ajax request.
In the request, a new feature
is pushed to fc.features
for every linestring in the geojson file. This works beautifully. What matters though is at the end: fc
is only complete after every feature has been iterated through (in this case there are 5 features). What I see in the console is every iteration of fc
after a new feature is added (it grows with each iteration and the fifth iteration produces the final json that is needed). However, I cannot access fc
outside of any of the functions as it turns up empty.
My goal is to write fc
to a json.file but I am unable to as I do not know how get around the issue of lexical scoping. Should I use a global variable or var _this = this;
? How would one access fc
after the five iterations?
var fc = {
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": []
}
$.getJSON("testROUTES.geojson", function (dat) {
$.each(dat.features, function (key, val) {
//reverse coordinates
val.geometry.coordinates = val.geometry.coordinates.map((coords) => {
return [coords[1], coords[0]]
});
line = val.geometry.coordinates;
var control = L.Routing.control({
router: L.Routing.osrmv1({
serviceUrl: 'http://127.0.0.1:5000/route/v1',
profile: 'driving'
}),
waypoints: line,
waypointMode: 'connect'
}).addTo(mymap);
control.on('routeselected', function(e) {
var lineCoordinates = [],
i,
latLng;
for (i = 0; i < e.route.coordinates.length; i++) {
latLng = L.latLng(e.route.coordinates[i]);
lineCoordinates.push([latLng.lng, latLng.lat]);
}
var json = {
"type" : "Feature",
"properties": {},
"geometry":
{
type: 'LineString',
coordinates: lineCoordinates
}
};
//console.log(json)
fc.features.push(json)
console.log(JSON.stringify(fc))
});
});
});