为什么点击功能不起作用?

时间:2016-04-14 02:00:56

标签: javascript html5 google-maps

请让我知道为什么点击功能在以下代码中无效:

<!DOCTYPE html>
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
    var map;
    var center = new google.maps.LatLng(11.17840187,122.59643555);
    var marker = new google.maps.Marker();
    var latitude;
    var longitude;

    function initialize() {
        var mapProp = {
           center : center,
           zoom : 5,
           mapTypeId : google.maps.MapTypeId.ROADMAP
        };
        map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
    }

    google.maps.event.addDomListener(window, 'load', initialize);

    google.maps.event.addListener(map, "click", function (event) {
        alert('You click the map!');
    });

    function moveToCenter(){
        map.panTo(center);
        marker.setPosition(center);
        marker.setMap(map);
    }

    function setWidth(width){
        document.getElementById('googleMap').style.width = width + "px";
        google.maps.event.trigger(map, 'resize');
    }

    function setHeight(height){
        document.getElementById('googleMap').style.height = height + "px";
        google.maps.event.trigger(map, 'resize');
    }
</script>
<style>
    body
    {
        padding : 0; 
        margin  : 0;
        overlow : hidden;
    }
    #googleMap
    {
        width  : 600px;
        height : 600px;
        overlow : hidden;
    }
</style>
</head>

<body>
<div id="googleMap"></div>
</body>
</html>

预期的结果应该是:每次点击地图时都会弹出警告对话框,但是没有发生。我已经在Google Chrome和Internet Explorer 8中对其进行了测试。

1 个答案:

答案 0 :(得分:1)

在初始化地图之前设置事件处理程序,在初始化地图后尝试将其放置

{{1}}