marker.addlistener在pageload之后立即被激活

时间:2015-10-23 14:23:54

标签: javascript google-maps google-maps-api-3 listener onclicklistener

这是我的代码,基于https://developers.google.com/maps/documentation/javascript/examples/event-simple的示例,但是当点击标记时,我想显示一个消息框(alert()):

<!DOCTYPE html>
<html>
  <head>
    <title>Simple click event - modified</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }
    </style>

  </head>
  <body>
    <div id="map"></div>
    <script>
function initMap() {
  var myLatlng = {lat: -25.363, lng: 131.044};

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: myLatlng
  });

  var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    title: 'Click to show alert'
  });

  marker.addListener('click', alert('Hello World!'));
}

    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&signed_in=true&callback=initMap" async defer>
    </script>
  </body>
</html>

当然,我从Google Maps API v3填写了自己的API密钥,而不是YOUR_API_KEY

每当我加载此页面时,只要页面加载就会显示警告,点击标记就完全没有效果。

1 个答案:

答案 0 :(得分:0)

问题出在addlistener,消息框的命令必须介于function() { ... }之间:

marker.addListener(   'click', function() {  alert('Hello World!');  }    );

将解决问题!

相关问题