Generic_User_ID
Generic_User_ID

Reputation: 1207

Google Maps API addListener method not working

I'm using Google Maps Javascript API, and I want to make it so that when you a click a button on a map, a JS alert pops up.

Here's my JS code so far:

var gmap = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

// Setting up and adding the boundary-changing buttons                                                  
var boundaryChangeArr = [
    '<h3 id="boundary-change-title">Change boundaries</h3>',
    '<div id="boundary-change-buttons-container">',
        '<input id="boundaries-states" class="boundary-change-button" type="button" name="StatesBoundaries" value="States" />',
        '<input id="boundaries-counties" class="boundary-change-button" type="button" name="CountiesBoundaries" value="Counties" />',
        '<input id="boundaries-tracts" class="boundary-change-button" type="button" name="TractsBoundaries" value="Tracts" />',
    '</div>'
];

// If there is no div  with the id 'boundary-change-container', make one
var boundaryChange = $('div#boundary-change-container');
if(boundaryChange.length===0){
    var boundaryChange = document.createElement('div');
    boundaryChange.id = 'boundary-change-container';
    boundaryChange.innerHTML = boundaryChangeArr.join('');
    gmap.controls[google.maps.ControlPosition.LEFT_BOTTOM].push(boundaryChange);
}; // DONE: if(boundaryChange.length===0)

google.maps.event.addListener(document.getElementById('boundaries-states'),
    'click',
    function(){
        alert('clicked');
    });

But when I click the button boundaries-states, nothing happens, and I don't even see any errors in Firebug, the Firefox plug-in that can check for JS errors.

What am I doing wrong?

Upvotes: 0

Views: 9922

Answers (1)

Brian S
Brian S

Reputation: 5785

Based on the comments and re-reading the question, you would like to perform some work when clicking on the Button not on the Google Map. In that case, you don't want to use google.maps.event.addListener since that will listen for events (like click) on the map itself.

For the button, you can use the jQuery click event or if you're using a different javascript framework, they will likely have a click event as well. For jQuery, you would do the following:

$('#boundaries-states').click(function () {
    //Do something
});

It looks like the addListener method takes the google Map object, not the HTML element for the map. Take a look at the first example here.

So if you're not already, you'll need to hold onto the reference to your map that is returned when you instantiate the map:

var map = new google.maps.Map(document.getElementById('boundaries-states'),
  mapOptions);

Once you have your map reference, you can add a listener using the map object, rather than the HTML element.

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

Upvotes: 1

Related Questions