简体   繁体   中英

Google Maps addListener does not work

In the HTML code below I want to have an alert when a map is changed (eg 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>   

This is because google.maps.event.addListener is called before the browser even knows about your maps object. Probably there are also console errors. Put this code into initialize() then it should work.

It would in general be recommendable to put all scripts shortly before the end of the body tag, after all HTML elements are defined including eg the div holding the map. Also the splitting of the scripts is kind of confusing and seems not to be necessary.

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");
  });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM