0

I'm collecting user input from an infowindow. On the infowindow, I have a button 'Save' to save user's input. But when I click that button, I also click on the map and it will make my marker move elsewhere. I just need to close the infowindow when clicking on button 'Save'. I don't want my marker move. Here's the code:

<body>
<script>
var infowindow, marker;
function initialize()
{
var myCenter = new google.maps.LatLng( 10.771654, 106.698285 );
var mapProp = {
center: myCenter,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("googleMap"),  
    mapProp);   

    var html = "<div>Comment:<br/>" +
           "<textarea id='text_map' cols='25' rows='4'></textarea>" + 
           "<input type='button' onclick='set_data()' value='Save'/>" + 
            "</div>";

    infowindow = new google.maps.InfoWindow({
         content: html
    });

    marker = new google.maps.Marker({
    });

    google.maps.event.addListener(map, 'click', function(event)      
    {                       
    var location = event.latLng;        
    marker.setPosition(location);
    marker.setMap(map);
        infowindow.open(map,marker);    

    });

    google.maps.event.addListener(marker, 'click', function() { 

       infowindow.open(map,marker);                     
    }); 
}

function set_data()
{
   //do something                     
   infowindow.close();                      
}
function loadScript()
{
   var script = document.createElement("script");
   script.type = "text/javascript";
   script.src = "http://maps.googleapis.com/maps/api" +    
   "/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false&callback=initialize";
   document.body.appendChild(script);
}
window.onload = loadScript;
</script>
<div id="googleMap" style="width: 500px; height: 500px"></div>

</body>
</html>

The weird thing is I don't have this problem on IE 9 but FireFox and CHROME.

EDIT:

To solve this problem I just need to stop event propagation. Here's how I do it: pass the event as argument of function set_data()

onclick='var event = arguments[0] || window.event; set_data(event)'

in set_data add this line of code:

e.stopPropagation();

Thanks Berend for the useful links.

crazy_in_love
  • 145
  • 3
  • 13

1 Answers1

0

An event will bubble up or capture down the dom tree. Alas for us IE uses a different model than Chrome and Firefox. See http://www.quirksmode.org/js/events_order.html

If not stopped, an event will continue being propegated up or down the DOM tree. This is what you experience: the click event is captured both by the button, and the map in chrome and Firefox. Since IE uses a different model, this does not happen in IE9.

To stop the event propagation use:

e.stopPropagation();

The solution is also discussed here How to stop event propagation with inline onclick attribute?

Community
  • 1
  • 1
Berend
  • 128
  • 1
  • 8