I'm pretty new to javascript and I'm learning as I go along, so sorry if this is simple.
What I have is a bunch of markers displaying on the map, these are loaded from an array and displayed with a function. What I want to do is make a specific div pop up which is related to the marker that was clicked on. When another marker is clicked, that previous div closes and the new div opens up.
This is what I have so far, to get a concept of what I'm doing.
I imagine I would want to write a function that says... "If 'Marker A' is clicked, open up 'div A' and if 'Marker B' is clicked while 'Marker A' is open, then close 'Div A' and open up 'Div B'.
Here's my javascript.
var markers = [
['Saving Grace', 43.652659,-79.412284],
['Starving Artist', 43.660281,-79.443570]
];
// Standard google maps function
function initialize() {
var myLatlng = new google.maps.LatLng(43.655826,-79.383116);
var image = 'http://www.brunchtoronto.com/images/marker-blue.png';
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Current Toggle function which displays Feature Box when marker is clicked
function opendiv() {
var ele = document.getElementById("div-feature");
ele.style.display = "block";
}
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < markers.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(markers[i][1], markers[i][2]),
map: map,
icon: image
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
map.panTo(marker.getPosition());
infowindow.setContent(markers[i][0]);
infowindow.open(map, marker);
opendiv();
}
})(marker, i));
}
}
And my HTML
<!-- Featued Window -->
<div class="featured_window" id="div-feature" style="display: none">
Stuff to display
</div>
<!-- Saving Grace -->
<div class="featured_window" id="div-sg" style="display: none">
Stuff to display
</div>
You need to have a relation between the marker and the div, currently there isn't any.
Instead of an ID like div-sg
this could be e.g. div0
, where the number indicates the index of the marker.
Then it's no problem to access the div:
//access the node
var content=document.getElementById('div'+i)
//create a copy of the node
.cloneNode(true);
//remove the id to avoid conflicts
content.removeAttribute('id');
//make it visible
content.style.display='block';
//apply the content and open the infoWindow
infowindow.setContent(content);
infowindow.open(map, marker);
来源:https://stackoverflow.com/questions/14387767/making-a-google-maps-marker-show-a-specific-div-when-clicked