0

Unsure of how to pass the returned value of getLocationsArray outside of the getLocations method. How would this be done so setMarkers method can use it? Of course, im aware when calling methods or vars internally within an object literal i can use APP.map.setMarkers for example. Thanks.

 init: function(){
   ...ETC...
  APP.map.getLocations()
  APP.map.setMarkers(center, radius, map)
},

getLocations: function() {
  $.getJSON('data/json/locations.json', function(data) {
    var locations = data
    var getLocationsArray = $.map(locations, function(value, index) {
      return [value]
    })
    console.log(getLocationsArray)
    return getLocationsArray
  })
  console.log('getLocationsArray2', getLocationsArray2)
  return getLocationsArray2
},

setMarkers: function(center, radius, map) {
  **getLocationsArray**.forEach (function (hello) {
  ..ETC..
}
sledgeweight
  • 7,685
  • 5
  • 31
  • 45

1 Answers1

1

$.getJSON will only deliver its result asynchronously, so you cannot use code that expects it to be available immediately. Instead use a callback system.

There is no use in returning a value inside the $.getJSON callback function: it will go to oblivion:

 return getLocationsArray // not useful.

You also refer to a variable getLocationsArray2 that is never initialised.

Instead, you could pass a callback argument:

init: function(){
  // ...ETC...
  // Pass an (anonymous) callback function to `getLocations`, which
  // it will call when the result is available. Then you can call
  // `setMarkers` to process that result.
  APP.map.getLocations(function (getLocationsArray) {
      APP.map.setMarkers(getLocationsArray, center, radius, map);
  });
},

getLocations: function(callback) {
  $.getJSON('data/json/locations.json', function(data) {
    var locations = data
    var getLocationsArray = $.map(locations, function(value, index) {
      return [value]
    })
    // If a callback function was provided, then call it now and
    // pass it the result.
    if (callback) callback(getLocationsArray);
  })
},

setMarkers: function(getLocationsArray, center, radius, map) {
  // We get the locations array as an argument now, so it is straightforward
  // to process it:
  getLocationsArray.forEach (function (hello) {
     ///..ETC..
}
trincot
  • 317,000
  • 35
  • 244
  • 286
  • Asynchronicity! ...ffs. Thank you. Further reading for others (and me) on this: http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron#answer-23667087 – sledgeweight Jul 13 '16 at 13:23