I'm trying to take a javascript array of arrays named "markers" that stores the name and street address of places that I want to add as markers on a Google Map.
var markers = [['Name of Place', '123 1st Street New York, NY'], ['Place 2', '122 1st Street, New York, NY']];
I have no problem making the map appear properly, or even making the marker appear with a title accessed from the "markers" array. As long as I access the title from the "markers" array explicitly. As shown below:
var map;
var geocoder;
function initMap(){
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 34.6760942, lng: -82.8386035},
zoom: 13
});
geocoder = new google.maps.Geocoder();
for(i = 0; i < markers.length; i++){
geocoder.geocode({'address': markers[i][1]}, function(results, status) {
if(status == 'OK'){
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: markers[0][0]
});
} else {
alert('Geocode was not successful because: ' + status);
}
});
}
}
However, I want to be able to use the index, "i", in the for loop to iteratively create these markers. If I try to iteratively grab the titles from the "markers" array using (title: markers[i][0]) as shown below. I get an "Uncaught type error: Cannot read property '0' of undefined.
var map; var geocoder;
function initMap(){
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 34.6760942, lng: -82.8386035},
zoom: 13
});
geocoder = new google.maps.Geocoder();
for(i = 0; i < markers.length; i++){
geocoder.geocode({'address': markers[i][1]}, function(results, status) {
if(status == 'OK'){
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: markers[i][0]
});
} else {
alert('Geocode was not successful because: ' + status);
}
});
}
}
For some reason, in the function the index, i, is not defined. How can I go about making sure "i" is defined inside the function?