gpt4 book ai didi

Javascript 数组在填充时显示 0 长度

转载 作者:行者123 更新时间:2023-12-02 20:29:15 26 4
gpt4 key购买 nike

我确信这真的很简单,但我没有太多运气找出问题所在。我正在创建一个空数组(位置),用 getPartnerLocations 函数中的位置对象填充它,然后尝试使用 drop 函数在 map 上绘制位置。我遇到的问题是,在 drop 函数内部,其中包含内容的位置数组返回的长度为零,因此其中的循环不起作用。任何关于这里发生的事情的提示或想法将不胜感激。

var markers = [];
var locations = [];
var iterator = 0;
var map;
var geocoder;
var newYork = new google.maps.LatLng(40.7143528, -74.0059731);


function initialize() {
var mapOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: newYork
};

map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);

}

function getPartnerLocations() {
geocoder = new google.maps.Geocoder();
$('.partner').each(function(index){

var street = $('.partner-streetaddress',this).text();
var city = $('.partner-city',this).text();
var state = $('.partner-state',this).text();
var country = $('.partner-country',this).text();

var address = street + ', ' + city + ', ' + state + ', ' + country;

geocoder.geocode( { 'address': address}, function(results, status)
{

if (status == google.maps.GeocoderStatus.OK)
{
locations.push( results[0].geometry.location );
console.log(locations[index]);
}
else
{
console.log('failed to geocode address: ' + address);
}
});

});
initialize();
drop();
}

function addMarker() {
console.log('add marker function');
markers.push(new google.maps.Marker({
position: locations[iterator],
map: map,
draggable: false,
animation: google.maps.Animation.DROP
}));
iterator++;
}

function drop()
{
console.log(locations.length);
for (var i = 0; i < locations.length; i++) {
setTimeout(function() {
addMarker();
}, i * 200);
}
}

getPartnerLocations();

最佳答案

geocode 是一个异步函数。

直到您调用drop之后一段时间后,回调才会执行。
因此,当您调用drop时,数组仍然是空的。

您需要在最后一次 AJAX 调用回复后在 geocode 回调中调用 initializedrop

关于Javascript 数组在填充时显示 0 长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4423660/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com