Neven Grguric Neven Grguric - 2 months ago 29
Javascript Question

Open Google Maps InfoWindow on link click outside of map

This is javascript I use to make all markers and set click listener

var infowindow = new google.maps.InfoWindow();
var markernovi, i;

for (i = 0; i < lokacije.length; i++) {
var ll = lokacije[i][2];
var latlng = ll.split(',');
markernovi = new google.maps.Marker({
position: new google.maps.LatLng(parseFloat(latlng[0]), parseFloat(latlng[1])),
map: mapObject,
icon: 'img/pins/' + key + '.png',
});

google.maps.event.addListener(markernovi, 'click', (function (markernovi, i) {
return function () {
infowindow.setContent(lokacije[i][0]);
infowindow.open(mapObject, markernovi);
}
})(markernovi, i));



markers.push(markernovi);
}
}


google.maps.event.addDomListener(window, 'load' , initialize);

function myClick(id){
google.maps.event.trigger(markers[id], 'click');
}


And I have this to list all locations on page :

<?php
foreach($lokacijebuy1 as $sve) {
?>
<div class="col-lg-6 col-md-12 col-sm-6">
<div class="img_wrapper">
<div class="img_container">
<a href="#" onclick="myClick(0);" >
<img src="http://evidentiraj.me/gkcard/slikemjesta/<?php echo $sve['photo']; ?>" width="800" height="533" class="img-responsive" alt="">
<div class="short_info">
<h3><?php echo $sve['ime2']; ?></h3>
<em><?php echo $sve['adresa']; ?></em>
<p>
<?php echo $sve['opis2']; ?>
</p>
</div>
</a>
</div>
</div><!-- End img_wrapper -->
</div><!-- End col-md-6 -->
<?php }
?>


And no matter which one I click only infowindow I open is the first one in array.

You can see page live here : http://evidentiraj.me/gorskikotarcard/locationsbuy.php

And I found that the only thing I need to change to display other marker is number inside myClick

<a href="#" onclick="myClick(1);" >


ANSWER:
only thing I did was to add counter in my
<a href
tag
Now it looks like this:

<?php
$counter = 0;
foreach($lokacijebuy1 as $sve) {

?>
<div class="col-lg-6 col-md-12 col-sm-6">
<div class="img_wrapper">
<div class="img_container">
<a href="#" onclick="myClick(<?php echo $counter; ?>);" >
<img src="http://evidentiraj.me/gkcard/slikemjesta/<?php echo $sve['photo']; ?>" width="800" height="533" class="img-responsive" alt="">
<div class="short_info">
<h3><?php echo $sve['ime2']; ?></h3>
<em><?php echo $sve['adresa']; ?></em>
<p>
<?php echo $sve['opis2']; ?>
</p>
</div>
</a>
</div>
</div><!-- End img_wrapper -->
</div><!-- End col-md-6 -->
<?php
$counter++;
}
?>

Answer

It's because you render the a element with function myClick with input argument set to 0, and you use this argument as an index in the markers array inside your function, which is still the first marker in the array. You need to change the way you render the a element to get results like this:

<a href="#" onclick="myClick(0);"></a>
<a href="#" onclick="myClick(1);"></a>
<a href="#" onclick="myClick(2);"></a>