javascript - JS 将对象添加到数组

标签 javascript arrays google-maps-api-3

我正在尝试使用以下代码将对象添加到数组:

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

我有 var 标记 = [];上面的代码开头是我的全局变量。目标是让标记[i]成为一个对象,可以在其他地方轻松访问它。我已经在函数内测试了标记[i],并且所有值都成功进入。但是,当我退出此函数并尝试调用包括标记[#] 在内的任何内容时,我被告知标记[#]未定义。 (我尝试过使用和不使用markers[i] = new Object;行)。为什么数组应该在其函数内工作而不是在其外部工作?

编辑说明 - 这是我到已显示部分的完整代码。标记数组在任何函数之外声明,并且(我认为)应该是全局的。

编辑原始编辑 - 这是我在最后一行尝试使用标记[#]的所有内容。它不属于任何函数。一些间距被搞乱了 - $(function() { 一直到“实例化映射”行下方。console.log 语句是函数外部的第一个内容。

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

最佳答案

您正在请求完成之前访问标记。标记应该是全局 promise ,或者应该从 onload 函数调用使用标记的函数。

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

关于javascript - JS 将对象添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36238570/

相关文章:

javascript - 谷歌地图,加载点上的纬度/经度

javascript - 在谷歌地图上使用 MarkerWithLabel 隐藏标记

google-maps - 融合表过滤条件或

javascript - document.ready 用于使用单个 JavaScript 文件的多种表单

javascript - 在javascript中,新的对象函数如何扩展同名的原型(prototype)函数?

javascript - 如何在 JavaScript 中逐行循环换行符分隔的 json?

javascript - 为什么我不能在 for-of 循​​环中将更新后的值赋给变量 'word' ?

python - 在 Python 中减去 numpy 数组时不需要的舍入

javascript - 指定单击链接时要加载的 xml 文件

javascript - 如何从一个组件发布事件并从nativescript中的另一个组件接收事件