Ajax callback and variable scope when loading JSON file into array

interwebjill

I am loading a geoJSON file using ajax so that I can push the coordinates of the geoJSON MultiPoint feature that is in the file into a (global) array for use in another function. I am having a problem with my callback function, I think. In the code below, I intend to load the data file and push the data pertaining to certain whales into the multipointCoords array. This works fine, but multipointCoords array is not available globally while whales is available. This is confusing me.

This code is also using OpenLayers.

    var whales = {};
    var multipointCoords = [];

    $.getJSON('data/BW2205005.geojson', function(data) {
        data.features.forEach(function(feature) {
            if (!whales.hasOwnProperty(feature.properties.name)) {
                whales[feature.properties.name] = {
                    "type": "FeatureCollection",
                    "features": []
                };
            }
            whales[feature.properties.name].features.push(feature);

            whales["Free Willy"].features.forEach(function(feature) {
                multipointCoords.push(feature.geometry.coordinates);
            });
                console.log(multipointCoords[0][0]);  // gives the right coordinate
        });
    });

    console.log(whales);  // is defined
    console.log(multipointCoords[0][0]); // is undefined

I have studied the following and still can't fix it:

How to load Open layers 3 geojson vector layer with bbox?

How do I return the response from an asynchronous call?

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

http://api.jquery.com/jQuery.getJSON/

Thanks for any help.

Rayon

While making ajax calls, we are uncertain about when the success callback will fire, hence we user callbacks in such situations. And pass function as an argument to the called function. In callback function we can pass the data retrieved in ajax response. I could see you are using global-variable in your snippet but you are using them synchronously, in that case value of global-variable is not updated(Values used before ajax success callback)

Try this:

function geoJSON(callback) {
  var whales = {};
  var multipointCoords = [];
  $.getJSON('data/BW2205005.geojson', function(data) {
    data.features.forEach(function(feature) {
      if (!whales.hasOwnProperty(feature.properties.name)) {
        whales[feature.properties.name] = {
          "type": "FeatureCollection",
          "features": []
        };
      }
      whales[feature.properties.name].features.push(feature);

      whales["Free Willy"].features.forEach(function(feature) {
        multipointCoords.push(feature.geometry.coordinates);
      });
      if (typeof callback === 'function') {
        callback(whales, multipointCoords);
      }
    });
  });
}
geoJSON(function(whales, multipointCoords) {
  console.log(whales);
  console.log(multipointCoords);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Hide loading gif after ajax callback

From Dev

Variable Scope in Nested AJAX Calls

From Dev

Javascript, outside variable scope in callback function?

From Dev

Javascript variable scope in callback?

From Dev

Passing variable in parent scope to callback function

From Dev

Callback when all ajax is loaded

From Dev

Loading Json as variable into jsTree

From Dev

Unbound variable error when loading a procedure from an external file

From Dev

Ajax error callback called when valid JSON is retuned

From Dev

Static variable file scope

From Dev

JQuery Ajax loading file with $.getScript callback passes unkown parameter

From Dev

Python: Error when loading file into numpy array

From Dev

PHP scope issue when loading page with ajax

From Dev

Modify scope variable through jQuery callback

From Dev

Ajax wont accept json when array

From Dev

Javascript variable scope in callback?

From Dev

ValueError when loading a json file (python)

From Dev

Loading data from a JSON file using jQuery and AJAX

From Dev

Ajax issue when loading json-file

From Dev

Perserving variable scope in callback

From Dev

JQuery Ajax loading file with $.getScript callback passes unkown parameter

From Dev

Jade loading a JSON file and assigning to variable

From Dev

loading each file of a folder as json array

From Dev

Using ajax json response in an angular scope variable

From Dev

class scope is lost within the ajax success callback

From Dev

Python callback variable scope

From Dev

Javascript function callback variable scope

From Dev

Ajax not loading the url file

From Dev

Delete array in JSON file with PHP and AJAX