0

I'm trying to add objects to an array with the following code:

    for (i = 0; i < tweet_object.length; i ++) {           
        markers[i] = new Object;
        markers[i] = {
            title:tweet_object[i].title,
            latitude:tweet_object[i].latitude,
            longitude:tweet_object[i].longitude,
            rating:tweet_object[i].importance
        };

I have var markers = []; above at the beginning of the code with my global variables. The goal is to have markers[i] be an object, which can easily be accessed elsewhere. I've tested markers[i] within the function, and all the values are successfully going in. However, when I get out of this function and try to call anything including markers[#], I am being told that markers[#] is undefined. (I've tried both with and without the markers[i] = new Object; line). Why should the array work within its function but not outside?

EDIT clarification - this is my full code up to the section already shown. The markers array is declared outside of any function and (I think) should be global.

EDIT to original edit - this is everything up to where I try to use markers[#], in the very last line. It's outside of any function. Some of the spacing got messed up - $(function() { goes all the way down to below the "instantiate map" line. The console.log statement is the first thing outside the function.

/*global json_tweet_data*/
/*global index*/

// Google Map
var map;

// markers for map
var markers = [];

// info window
var info = new google.maps.InfoWindow();

// execute when the DOM is fully loaded
$(function() {

function reqListener ()
{
  //console.log(this.responseText);
}

var oReq = new XMLHttpRequest(); //New request object
oReq.onload = function()
{
    var json_tweet_data = this.responseText;
    var tweet_object = JSON.parse(json_tweet_data);

    //CREATE MARKERS FOR NEWS ITEMS
    for (i = 0; i < tweet_object.length; i ++) {
        //console.log("Latitude for " + i + ": " + tweet_object[i].latitude);
        //console.log("Longitude for " + i + ": " + tweet_object[i].longitude);

        markers[i] = {
            title:tweet_object[i].title,
            latitude:tweet_object[i].latitude,
            longitude:tweet_object[i].longitude,
            rating:tweet_object[i].importance
        };
        //console.log(i + ": " + JSON.stringify(markers[0]));
        if (tweet_object[i].latitude !== 0 && tweet_object[i].longitude !== 0) {
            var myLatLng = {lat: parseFloat(tweet_object[i].latitude), lng: parseFloat(tweet_object[i].longitude)};
            //console.log(tweet_object[i].title);
            //console.log("LatLng: " + myLatLng.lat + ", " + myLatLng.lng);
            //console.log("Rating: " + tweet_object[i].importance);
            if (tweet_object[i].importance <= 40) {
                var marker = new google.maps.Circle({
                    strokeColor: '#0000FF',
                    strokeOpacity: .8,
                    strokeWeight: 2,
                    fillColor: '#0000FF',
                    fillOpacity: .4,
                    radius: 160000,
                    map: map,
                    center: myLatLng
                });
            }
            else if ((tweet_object[i].importance <= 80) && (tweet_object[i].importance > 40)) {
                var marker = new google.maps.Circle({
                    strokeColor: '#00FFFF',
                    strokeOpacity: .8,
                    strokeWeight: 2,
                    fillColor: '#00FFFF',
                    fillOpacity: .4,
                    radius: 160000,
                    map: map,
                    center: myLatLng
                });
            }
            else if ((tweet_object[i].importance <= 120) && (tweet_object[i].importance > 80)) {
                var marker = new google.maps.Circle({
                    strokeColor: '#00FF00',
                    strokeOpacity: .8,
                    strokeWeight: 2,
                    fillColor: '#00FF00',
                    fillOpacity: .4,
                    radius: 160000,
                    map: map,
                    center: myLatLng
                });
            }
            else if ((tweet_object[i].importance <= 160) && (tweet_object[i].importance > 120)) {
                var marker = new google.maps.Circle({
                    strokeColor: '#00FF66',
                    strokeOpacity: .8,
                    strokeWeight: 2,
                    fillColor: '#00FF66',
                    fillOpacity: .4,
                    radius: 160000,
                    map: map,
                    center: myLatLng
                });
            }
            else if (tweet_object[i].importance > 160) {
                var marker = new google.maps.Circle({
                    strokeColor: '#FF0000',
                    strokeOpacity: .8,
                    strokeWeight: 2,
                    fillColor: '#FF0000',
                    fillOpacity: .4,
                    radius: 160000,
                    map: map,
                    center: myLatLng
                });
            }
        };
    }
};
oReq.open("get", "variables_for_js.php", true);
oReq.send();

// options for map
// https://developers.google.com/maps/documentation/javascript/reference#MapOptions
var options = {
    center: {lat: 39.8282, lng: -98.5795}, // Geographic center of contiguous 48 US states
    disableDefaultUI: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    maxZoom: 14,
    panControl: true,
    styles: styles,
    zoom: 2,
    zoomControl: true
};

// get DOM node in which map will be instantiated
var canvas = $("#map-canvas").get(0);

// instantiate map
map = new google.maps.Map(canvas, options);
});

console.log("Testing: " + JSON.stringify(markers[0]));
Mettler
  • 41
  • 5
  • ` when I get out of this function` what is that function? – Rajaprabhu Aravindasamy Mar 26 '16 at 17:40
  • 1
    Are you sure it's defined high enough in the structure to truly be global? Sounds like you're dealing with a scope issue even though you've tried to plan for it. – ThrowBackDewd Mar 26 '16 at 17:40
  • 5
    You don't need the line `markers[i] = new Object;` - the subsequent line creates a new object and obliterates the original one anyway. – Pointy Mar 26 '16 at 17:40
  • Could the function involved perhaps be a callback to some asynchronous operation, like an ajax call or a Google maps API call? – Pointy Mar 26 '16 at 17:41
  • You might not be declaring your markers array in the global scope. Can you post more of your code? Variables declared within a function will only be accessed from within that function. – joemillervi Mar 26 '16 at 17:47
  • Your code is working fine [here](https://jsfiddle.net/4castle/3m2n2397/1/). Please explain how your code is different from my code. Your problem is not reproducible. – 4castle Mar 26 '16 at 18:04
  • @Pointy, the data in tweet_object[i] is coming from the call above, but my understanding is that the data brought by the call was put into the tweet_object object, and should now be accessible throughout the program. Is that incorrect? – Mettler Mar 26 '16 at 18:49

1 Answers1

1

You are accessing markers before the request completes. Markers should be a global promise or the function the uses markers should be called from the onload function.

// Executes 1st
oReq.onload = function()
{
    // Executes 3rd
};
oReq.send();
//oReq is async so exicution contiunes before the request is complete
// Executes 2nd
console.log("Testing: " + JSON.stringify(markers[0]));
  • Sorry about the lack of clarification, I've edited my post to display the full code up until the loop. Markers was declared at the beginning of the program, so it should have global scope. – Mettler Mar 26 '16 at 18:46
  • Just put in code for the entire program - I try to access markers[] in the last line. – Mettler Mar 26 '16 at 19:07
  • Understood. I can create the function I wanted to call markers[] for inside the onload function anyway, if that will solve the problem. Just so I understand how I would handle this if I had to make the array work outside of the function, how would I make markers a global promise? – Mettler Mar 26 '16 at 19:20
  • @Mettler assign the promise to a variable and use .then –  Mar 26 '16 at 19:24