jcbridwe jcbridwe - 1 year ago 59
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
loop to iterate through each Job. The
variable is then given a value by using the
Leaflet method on the marker created for each job. My problem is that when I try to call the
variable (I'm testing using
) 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
inside another request, but it works fine for the global

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


Answer Source

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']

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download