如何处理ajax请求中的范围

时间:2017-07-21 04:49:21

标签: javascript json ajax scope

我在fc ajax请求之前定义了变量getJSON()

在请求中,对于geojson文件中的每个线串,新的feature被推送到fc.features。这很好用。重要的是最后:fc仅在每个特征迭代完成后才完成(在这种情况下有5个特征)。我在控制台中看到的是在添加新特征后每次迭代fc(它随着每次迭代而增长,第五次迭代产生所需的最终json)。但是,我无法在任何功能之外访问fc,因为它变空了。

我的目标是将fc写入json.file,但我无法解决,因为我不知道如何解决词法范围问题。我应该使用全局变量还是var _this = this;?如何在五次迭代后访问fc

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

        });
    });
});

0 个答案:

没有答案