Reputation: 1
I have an array outside the geocoder, but when I want to use that array inside geocoder the values of the array are undefined
var titles = new Array(<?php echo implode(",",$titles); ?>);
var length = postCode.length;
for (var i = 0; i < length; i++)
{
geocoder.geocode({'address': postCode[i]}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
lat2 = results[0].geometry.location.lat();
lng2 = results[0].geometry.location.lng();
var Latlng = new google.maps.LatLng(lat2, lng2);
var marker = new google.maps.Marker({
position: Latlng,
map: map,
title: titles[i],
icon: icon});
// alert(titles[i]) - all undefined
}
}
}
Upvotes: 0
Views: 75
Reputation: 161334
The geocoder is asynchronous. The loop spins through all the possible values of i, leaving i set to postCode.length+1 which is undefined. This can be addressed with function closure (however, depending on the number of locations you have, you may have issues with the quota or rate limit):
function geocodeAddress(index) {
geocoder.geocode({'address': postCode[index]}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat2 = results[0].geometry.location.lat();
var lng2 = results[0].geometry.location.lng();
var Latlng = new google.maps.LatLng(lat2, lng2);
var marker = new google.maps.Marker({
position: Latlng,
map: map,
title: titles[index],
icon: icon
});
} else { alert("geocode failed:"+status);
});
}
for(var i = 0; i < length; i++)
{
geocodeAddress(i);
}
Upvotes: 1
Reputation: 18462
You could just do
var titles = <?php echo json_encode($titles); ?>;
Upvotes: 2