开发者

How can I remove all instances/custom objects created of one class?

开发者 https://www.devze.com 2023-03-29 21:18 出处:网络
I need some help with JavaScript and Google Maps API. I have a Google Maps map on my website which shows markers, which in turn show a custom InfoBox when clicked on.

I need some help with JavaScript and Google Maps API.

I have a Google Maps map on my website which shows markers, which in turn show a custom InfoBox when clicked on.

When a marker is clicked, a new object is created for this InfoBox:

google.maps.event.addListener(marker, 'click', function() {
    infoBox = new InfoBox({id: id, content: description, latlng: marker.getPosition(), map: map});
});

When a visitor clicks two markers consecutively, he is faced with two InfoBoxs. I run two lines of code that hide the InfoBoxs when a users clicks away in the map or when they click the cross in the upper right corner:

google.maps.event.addDomListener(closeImg, 'click', removeInfoBox(this));
google.maps.event.addDomListener(map, 'click', removeInfoBox(this)); 

What I would like to happen is that when a user clicks on a marker, all previous markers will get hidden (so after each click on a marker, there would only be one previous InfoBox to be hidden).

I'm struggling to get this done. If I create a DomListener on all markers with the 'click' event, I never get an InfoBox to pop up. If I put removeInfoBox(this); before creating a new object of InfoBox I also nev开发者_StackOverflow社区er get shown an InfoBox.

Where and how would be the proper way to prevent more than one InfoBox from showing up?


I found a post on how to remove markers and keep track of them which I could adept to my script.

First I declare the array for storing opened infoBox'es and the function to remove them (clearOverlays()):

// Declare global array for hiding infowindows
var infowindowsArray = [];

function clearOverlays(){
    if(infowindowsArray){
        for (i in infowindowsArray){
            infowindowsArray[i].setMap(null);
        }
    }
}

Then when I create a listener for the marker's click event, it will add the new infoBox to that marker. First I use the clearOverlays() function to clear all other infoBox'es. Then I create the new infoBox and push it into the array:

google.maps.event.addListener(marker, 'click', function() {
    clearOverlays();
    infoBox = new InfoBox({id: id, content: description, latlng: marker.getPosition(), map: map});
    infowindowsArray.push(infoBox);
});

This solved my problem with the custom created infoBox'es.

0

精彩评论

暂无评论...
验证码 换一张
取 消