[Google Maps] How to show only one infowindow for multiple map markers.

[Google Maps] How to show only one infowindow for multiple map markers.

  
Forge Component
(13)
Published on 20 Sep (8 days ago) by OutSystems Labs
13 votes
Published on 20 Sep (8 days ago) by OutSystems Labs
I recently added Google Maps to our Real Estate Market Statistics application. I was really pleased with how easy it was able to accomplish this enhancement using the Google Maps component. When I presented the application to my client they too were very impressed. They had one change request: "If an info window is open and I click on another marker please close the existing info window so there is only one info window open."

This sounded like a very reasonable request but not being a javascript expert it took me a couple of days to figure out how to do this. From all the research I did on the subject it appeared that the best method to accomplish this was to reuse a single info window which for me was easier said then done!

So if anyone needs to do this here is how I accomplished the task.

First in the application javascript I added:

function setinfowindow()
{
    var infowindow = new google.maps.InfoWindow();
    return infowindow;
}
    
function createinfowindow(infowindow,content)
{   
    infowindow.close();
    infowindow = new google.maps.InfoWindow({content:content});
    return infowindow;
}

And then I changed the marker javascript to this:

"
function() {
    if (typeof infowindow === 'undefined')
    {
    infowindow = setinfowindow();
    }
    var contentString = 
    '<h3 style=\'margin:0\'>Hawaii Island</h3>'+
    '<strong>District = Kau</strong><br>';

    infowindow = createinfowindow(infowindow,contentString); 
    infowindow.open(this.getMap(), this);

    var inputObject = document.getElementById('"+DistrictInputBigIsland.Id+"');
    inputObject.value = 'Kau';
    
    var buttonObject = document.getElementById('"+SubmitDistrictBigIsland.Id+"');
    buttonObject.click();
}"

Works great!

I hope this will save you all some time if you want to include this functionality into your Google Maps application.
Awesome, Gregg! Great to know you were able to work it out, even thought you're not (supposedly) a JavaScript expert.

Off the top of my head, I'd do that too, since I think Google's API doesn't offer a way into opened InfoWindows on a map (that would've been ideal).

Thanks for sharing it with us and be sure to let us know if we can help!