views:

45

answers:

1

I've seen the other posts, but they dont have the markers being looped through dynamically like mine. How do I create an event that will close the infowindow when another marker is clicked on using the following code?

$(function(){
    var latlng = new google.maps.LatLng(45.522015,-122.683811);
    var settings = {
        zoom: 10,
        center: latlng,
        disableDefaultUI:false,
        mapTypeId: google.maps.MapTypeId.SATELLITE
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), settings);

    $.getJSON('api',function(json){
        for (var property in json) {
            if (json.hasOwnProperty(property)) {
                var json_data = json[property];
                var the_marker = new google.maps.Marker({
                    title:json_data.item.headline,
                    map:map,
                    clickable:true,
                    position:new google.maps.LatLng(
                        parseFloat(json_data.item.geoarray[0].latitude),
                        parseFloat(json_data.item.geoarray[0].longitude)
                    )
                });
                function buildHandler(map, marker, content) {
                    return function() {
                        var infowindow = new google.maps.InfoWindow({
                            content: '<div class="marker"><h1>'+content.headline+'</h1><p>'+content.full_content+'</p></div>'
                        });
                        infowindow.open(map, marker);
                    };
                }
                new google.maps.event.addListener(the_marker, 'click',buildHandler(map, the_marker, {'headline':json_data.item.headline,'full_content':json_data.item.full_content}));
            }
        }
    });
});
A: 

I finally figured it out... no thanks to anyone here... It was actually fairly easy:

First, set up some vars to store the infowindow:

var infowindow;

Then add this to wherever your onClick function is that triggers the other infowindow.open(). Put it above the open though:

if(infowindow) {infowindow.close()}

Inside your loop or however else you are adding markers.

E.g. in full action:

At the very top of my script:

var infowindow;

Inside my loop of adding markers:

function buildHandler(map, marker, content) {
    return function() {
        if(infowindow) {infowindow.close()}
        infowindow = new google.maps.InfoWindow({
            content: 'My Content here'
        });
        infowindow.open(map, marker);
    };
}
Oscar Godson