jcbridwe jcbridwe - 3 months ago 9
Ajax Question

Global variable only returns value from the last instance in a loop

I've created a global variable outside of an ajax request;

var pos = [];
to collect latitude and longitude information of specific "jobs" coming from my api. "Jobs" also has it's own global variable outside the ajax request to collect an array of the data for each job (
var Jobs = [];
). Inside the ajax request, I have used the generic
Jobs = data
to set the variable value to the data being gathered in the request upon success (
success: function (data) {Jobs = data; ...
). I then use a
Jobs.forEach
loop to iterate through each Job. The
pos
variable is then given a value by using the
.getLatLng
Leaflet method on the marker created for each job. My problem is that when I try to call the
pos
variable (I'm testing using
console.log(pos);
) outside of the forEach loop, it only spit's back the last instance. Any suggestions on what I am doing wrong? My simplified code is below. Note: I am trying to call
pos
inside another request, but it works fine for the global
Jobs
variable.

var grid = L.geoJson();
var Jobs = {};
var pos = [];

//var control = L.control.layers(grid).addTo(map);
// This is the ajax request for the jobs data
$.ajax({
type: 'GET',
url: url,
timeout: 8000,
crossDomain: true,
dataType: 'json',
data: Jobs,
...

//Renders data to view
success: function (data) {
Jobs = data;
Jobs.forEach(function (value) {
console.log (pos);
...
var latitude = value.latitude;
var longitude = value.longitude;
...

var marker = L.marker([value.latitude, value.longitude]).addTo(map);
pos = marker.getLatLng();
...
console.log (pos);
});

// Fetch the file data making the grid
$.getJSON('./grid.geojson', function (data) {
// Assign the results to the geojsonData variable

console.log(Jobs);
console.log(pos);

Answer

You are overwriting the pos variable each time with a new marker. pos = marker.getLatLng();

Instead you need to .push the new values into the array, this will add each new value in to the array

pos.push(marker.getLatLng()); //['marker1']

Then the next time the loop runs, the next marker will be added

pos.push(marker.getLatLng()); //['marker1', 'marker2']

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/push