Monday, June 18, 2012

Stop the click event from propagating from the Google Maps marker InfoWindow

I was writing Google Maps Javascript code to delete a marker already placed on the map by clicking a 'delete' link on the marker's InfoWindow. However, a new marker kept getting placed at the location of the delete link. The problem is illustrated in the before and after screenshots below.

After reading up, I figured out that the click event on the InfoWindow link was being propagated down to the map's onclick event listener. To prevent this from happening, the click event must be stopped from being propagated down.

The following code snippet illustrates how to stop the propagation.
//Create a new marker on this map
var mkr = new google.maps.Marker({
    icon: icon,
    shadow: shadow,
    position: point, 
    id: id, 
    desc: desc,
    title: desc,
    map: this.map
});

//Now create the infowindow object that will be attached to the marker
var contentString;
//Create a div element with an ID to contain the info window contents
contentString = '<div id="infoDiv" >';
contentString += "<textarea rows='3' cols='25' onclick='this.select();'>";
contentString += desc;
contentString += "</textarea>" + "<br />";
contentString += "<a href='#' onclick='onMkrInfoDeleteClick()'>Delete</a>|";
contentString += "<a href='#' onclick='onMkrInfoOkClick()'>Ok</a>";
contentString += '</div>';
var infoWnd = new google.maps.InfoWindow({content: contentString});
google.maps.event.addListener(mkr,'click',
    function(evt){
        infoWnd.open(this.map,mkr);
    }
);
//call this function when the InfoWindow's Delete link is clicked    
function onMkrInfoDeleteClick(){
    //get the pointer to the InfoWindow div element
    var div = document.getElementById('infoDiv');
    if (div)
        //cancel the click event so that it doesn't propagate to the map object below the InfoWindow
        google.maps.event.addDomListener(div, 'click', 
            function (evt){
                evt.cancelBubble = true;
                if (evt.stopPropagation)
                    evt.stopPropagation();
            }        
        );
    // Erase the clicked marker 
    mkr.setMap(null);
};

No comments: