Reputation: 83
i'm created a google maps with javascript on my html page and i have multiple markers and infowindows.
my infowindows visible when user click marker but i want to do all infowindows visible on page load.
var locations = [
['TRY 620', 36.888932, 30.683421],
['TRY 772', 36.872729, 30.718440],
['TRY 120', 36.870532, 30.640505],
['TRY 32', 36.854875, 30.739554],
['TRY 600', 36.900189, 30.632437]
];
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: searchItemMap
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
}
})(marker, i));
infowindow.open(searchItemMap, marker);
}
Upvotes: 1
Views: 5169
Reputation: 161334
One option with your code would to be attach the marker's unique infowindow as a property of the marker, with the correct contents, then use this
inside the marker click listener to reference the marker (then you don't need function closure).
marker._infowindow = new google.maps.InfoWindow({content: locations[i][0]});
google.maps.event.addListener(marker, 'click', function() {
this._infowindow.open(searchItemMap, this);
});
// open marker on load
google.maps.event.trigger(marker,'click');
code snippet:
function initialize() {
var searchItemMap = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: searchItemMap
});
bounds.extend(marker.getPosition());
marker._infowindow = new google.maps.InfoWindow({
content: locations[i][0]
});
google.maps.event.addListener(marker, 'click', function() {
this._infowindow.open(searchItemMap, this);
});
// open marker on load
google.maps.event.trigger(marker, 'click');
}
searchItemMap.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initialize);
var locations = [
['TRY 620', 36.888932, 30.683421],
['TRY 772', 36.872729, 30.718440],
['TRY 120', 36.870532, 30.640505],
['TRY 32', 36.854875, 30.739554],
['TRY 600', 36.900189, 30.632437]
];
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
Upvotes: 1