Mettler
Mettler

Reputation: 41

JS adding object to an array

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]));

Upvotes: 0

Views: 79

Answers (1)

user6101582
user6101582

Reputation:

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]));

Upvotes: 1

Related Questions