Reputation: 193
I have a google map and I want the first window to open when the page loads, but my coding I have now opens ALL the windows. See JS here:
var markers = [];
function initialize() {
// Map options
var mapOptions = {
scrollwheel: false,
zoom: 6,
center: new google.maps.LatLng(-1.919502, 36.256042),
mapTypeId: google.maps.MapTypeId.TERRAIN
}
// Create a map
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
// Set locations and content
var locations = [
['A', -1.919502, 36.256042, 'https://i.sstatic.net/JWM0W.png'],
['B', -2.079736, 34.401916, 'https://i.sstatic.net/JWM0W.png'],
['C', -1.246850, 35.158567, 'https://i.sstatic.net/JWM0W.png'],
['D', -4.696879, 36.734848, 'https://i.sstatic.net/JWM0W.png'],
['E', -7.972198, 32.880363, 'https://i.sstatic.net/JWM0W.png'], ];
// Markers positions
var marker, i;
// For each point on the location put a marker
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: locations[i][3]
});
// Activiate markers and infowindow to open on click of a link
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
markers.push(marker);
// Set the first info window to appear on page load
var infowindow = new google.maps.InfoWindow();
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
// Create Polylines
var trackerRouteCoordinates = [
new google.maps.LatLng(-1.919502, 36.256042),
new google.maps.LatLng(-2.079736, 34.401916),
new google.maps.LatLng(-1.246850, 35.158567),
new google.maps.LatLng(-4.696879, 36.734848),
new google.maps.LatLng(-7.972198, 32.880363), ];
var trackerPath = new google.maps.Polyline({
path: trackerRouteCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 0.1,
strokeWeight: 3
});
trackerPath.setMap(map);
}
}
// Load map on window load
google.maps.event.addDomListener(window, 'load', initialize);
// Create the function that triggers a click on a link to show a marker
function myClick(id) {
google.maps.event.trigger(markers[id], 'click');
}
I am completely new here and this will be a quick fix but I'm not too good at Javascript so can anyone help. See the js fiddle if you want: http://jsfiddle.net/clockingowlhours/3JfdP/23/
Upvotes: 0
Views: 453
Reputation: 2459
You are opening infowindow every time in for loop. You need to add an if
control to open only first infowindow. Update your code as below:
...
// Set the first info window to appear on page load
if(i == 0) {
var infowindow = new google.maps.InfoWindow();
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
// Create Polylines
...
Upvotes: 1