Shagglez
Shagglez

Reputation: 1522

Attaching a click event to a Google map

I can't seem to figure out how to attach a click event to a Google map, is it only possible to do so on the marker? This doesn't seem to do anything:

google.maps.event.addListener(map, 'click', function() {
    console.log('clicked');
});

I've also tried using jQuery, but that catches two events, I'm guessing something to do with overlays: EDIT: some idiot initiated the map twice, and attached the event in the same function, hence two events. jQuery works just as well, and in fact can handle more events.

$('#placeholder').click(function() {console.log('clicked');});

Am I missing something?

Upvotes: 0

Views: 329

Answers (2)

Galen
Galen

Reputation: 30170

Maybe your map name is incorrect? Show us your entire code.

Here's an example of attaching a click event handler to a map

http://jsfiddle.net/galen/EXRSD/

Upvotes: 1

capdragon
capdragon

Reputation: 14899

Your code works for me. try (Ctrl + F5) to reload page without cache.

<!DOCTYPE html> 
<html> 
<head> 
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
<style type="text/css"> 
  html { height: 100% }
  body { height: 100%; margin: 0px; padding: 0px }
  #map_canvas { height: 100% }
</style> 
<title>Google Maps Example</title> 
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script> 
<script type="text/javascript">
    function initialize() {
        var myLatlng = new google.maps.LatLng(-34.397, 150.644);
        var myOptions = {
            zoom: 3,
            center: myLatlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

        google.maps.event.addListener(map, 'click', function () {
            console.log('clicked');
        });
    }
</script> 
</head> 
<body onload="initialize()"> 
  <div id="map_canvas"></div> 
</body> 
</html> 

Upvotes: 1

Related Questions