0

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))

        });
    });
});
iskandarblue
  • 7,208
  • 15
  • 60
  • 130
  • Likely a duplicate of https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call - also look into promises – mplungjan Jul 21 '17 at 04:54
  • Are you sure that's your full code? It should work. Only reason it wouldn't is if you are declaring fc as a variable inside a function. Try qualifying fc with window.fc – Alexander Higgins Jul 21 '17 at 04:58
  • that's the full code - `fc.features` after the getJSON() request is empty and is also empty outside of the last function. I am not using a framework – iskandarblue Jul 21 '17 at 05:00
  • Looks like your doing `fc.features.push(json);` inside `control.on('routeselected', `... so it makes sense it'd wait until 'routeselected' before adding `json` to `features`. – Rocky Sims Jul 21 '17 at 05:03
  • Is `console.log(JSON.stringify(fc))` spitting out the expected result of 5 features? – Rocky Sims Jul 21 '17 at 05:05
  • Yes - first it logs the first feature, then the first + second feature, then the first + second + third feature... and so on until all features are in `fc`. Console.log runs five times, once for every added feature – iskandarblue Jul 21 '17 at 05:06
  • My guess is `fc` turns up empty (as you put it in your question) because your checking it's value before the `control.on` handler function runs. Maybe try adding a button that when clicked prints `fc` to console and click that button after `fc` has the 5 features. I'll bet you `fc` will show up as having the 5 features when you click the test button. – Rocky Sims Jul 21 '17 at 05:13
  • Something like `$(".myTestButton").click(function() {console.log("fc: ", fc)});` – Rocky Sims Jul 21 '17 at 05:14
  • I added this at the end - but `fc.features` is empty: `var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(fc)); $('download JSON').appendTo('#container');` – iskandarblue Jul 21 '17 at 05:17
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/149767/discussion-between-rocky-sims-and-the-darkside). – Rocky Sims Jul 21 '17 at 05:20

0 Answers0