henk henk - 2 months ago 17
Javascript Question

Google Maps addListener does not work

In the HTML code below I want to have an alert when a map is changed (e.g. zooming, dragging, clicking).

That alert will be changed in future to show the corner coordinates when dragging, zooming or clicking. The button "Get Corners" will then be omitted (that works perfect now).

I have tried a lot of advices from numerous websites. But still no success.

The addListener for the alert does not work. Also using addDomListener instead does not work. What is the culprit in this code?

Thanks for your help in advance!

<!DOCTYPE html>
<html>
<head>
</head>
<script src="http://maps.googleapis.com/maps/api/js">
</script>

<body>
<script>
var map;
function initialize()
{
var mapOpt = {center:new google.maps.LatLng(41.5,2.0),zoom:10, mapTypeId:google.maps.MapTypeId.SATELLITE};
map=new google.maps.Map(document.getElementById("googleMap"),mapOpt);
};
</script>

<script>
function getCorners()
{
var bounds = map.getBounds();
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
document.getElementById('ne').innerHTML = ne;
document.getElementById('sw').innerHTML = sw;
}
</script>

<! THIS addListener SCRIPT DOES NOT WORK>
<script>
google.maps.event.addListener(map, 'idle', function()
{
window.alert("Map clicked");
});
</script>

<script>
google.maps.event.addDomListener(window, "load", initialize);
</script>
<p id="ne">NE</p>
<p id="sw">SW</p>
<button onclick="getCorners()">Get Corners</button>

<br><br>
<div id="googleMap" style="width:500px;height:500px"></div>
</body>
</html>

Answer

Try move the listener code inside the initilize function

function initialize()
{
  var mapOpt = {center:new google.maps.LatLng(41.5,2.0),zoom:10, mapTypeId:google.maps.MapTypeId.SATELLITE};
  map=new google.maps.Map(document.getElementById("googleMap"),mapOpt); 
  google.maps.event.addListener(map, 'idle', function(){
      window.alert("Map clicked");
  });
};