Timothy Hill Timothy Hill - 10 days ago 4
Javascript Question

Open div instead of infowindow by clicking marker on Google Maps

I have a full screen Google Map that has a small div at the bottom to hold images that turn markers on and off. I also have a hidden div that holds information for each marker (that would normally appear in the infowindow).

I want to be able to show() or fadein() the hidden div when the marker is clicked on the map. This is how I am adding markers.

for (i = 0; i < locations.length; i++) {
var myLatLng = new google.maps.LatLng(locations[i][1], locations[i][2]);
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][2], locations[i][2]),
icon: icons[locations[i][4]].icon,
map: map,
id: locations[i][3],
type: locations[i][4]
});
markerGroups[locations[i][4]].push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
toggleWindow(marker.id);
})(marker, i));
bounds.extend(myLatLng);
}
if (locations.length > 0){
map.fitBounds(bounds);
}


Each location in the array looks like this:
["1.50 inches", 37.5, -77.33, 0, "hail150"]

The toggle window function is:

function toggleWindow(id){
var godiv = '#sr'+id;
if ($(godiv).css('display') == 'block') {
$(godiv).css('display', 'none');
}
else {
$("#reportframe").children().hide();
$(godiv).css('display', 'block');
};
};


When you click on a marker I get an error:

Uncaught TypeError: Cannot read property 'apply' of undefined (main.js:17)

I have tried it several different ways but it appears that the IDs are not matching up or GMaps doesn't have access to the var.

Fiddle

Answer

The function-call which has been used as click-handler must return a function(the returned function will be the handler). Currently the function will return nothing, and the "nothing" is the undefined in the error-message.

so it has to be e.g:

google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function(){toggleWindow(marker.id);}
})(marker, i));

SEE DEMO