I'm trying to create a slider with 3 slides, each containing a mini map with marker pointing to certain location. I managed to create one slide, but every attempt to create more than one on this page results in failure. Here is my code so far:
HTML + PHP
<?php if (have_rows('job_offers')): ?>
<?php
$rows = get_field('job_offers');
$row_count = count($rows);
for ($i = 0; $i <= 2; $i++) {
?>
<li>
<div id='googleMap<?php echo $i; ?>' style="position:absolute;top:0;right:0;width:180px;height:100%;"></div>
</li>
<?php } ?>
<?php endif; ?>
and jQuery
var geocoder = new google.maps.Geocoder();
var map;
var locations = ["London",'Paris','Barcelona'];
var pos;
function initialize()
{
google.maps.visualRefresh = true;
getGeoCode();
}
function getGeoCode()
{
for (var i=0; i<3 ; i++) {
geocoder.geocode({'address': locations[i]}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK)
{
pos[i] = results[0].geometry.location;
var mapOptions = {
zoom: 8,
center: pos[i],
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
styles: [
{ stylers: [{hue:'#C4268C'},{lightness:-60},{saturation:100}]}
]
};
map[i] = new google.maps.Map(document.getElementById("googleMap" + i), mapOptions);
var image = '<?php echo get_template_directory_uri(); ?>/images/marker.png';
var marker = new google.maps.Marker({
position: pos[i],
icon:image
});
marker.setMap(map[i]);
}
else
{
alert("Not found");
}
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
When I didn't try to use arrays, everything was fine. I'll be grateful for any hints. Cheers, E.
The code below fixes the problem with function closure (them makeMap function holds closure on the value of "i" for use when the geocoder callback runs):
Working fiddle
code snippet: