Google Maps API google.maps.event未定义

时间:2010-12-20 05:22:08

标签: google-maps javascript-events

我正在尝试使用Google Maps API来获取用户提供的位置。为此,我设置了一个基于“点击”事件移动的标记。代码是这样的:

function initialize_google_map(div_id) {
    var map = new GMap2(document.getElementById(div_id));

    map.setCenter(new GLatLng(45, -105), 2);

    map.setUIToDefault();

    return map;
}

$(document).ready(function() {
    // configure the google maps api
    var map = initialize_google_map("map_canvas");
    var marker = google.maps.Marker({map: map, title:"Location"});
    google.maps.event.addListener(map, "click", function(evt) {
        alert("got click event");
        marker.setPosition(evt.latLng);
    });

    $(document).unload(function() {
    // unload the google map
    GUnload();
    }); 

});

“点击事件”警告从未触发,我的Javascript控制台(谷歌浏览器)说:     Uncaught TypeError: Cannot call method 'addListener' of undefined

API就像这样包括在内 <script src="http://maps.google.com/maps?file=api&v=3&sensor=true" type="text/javascript"></script>

2 个答案:

答案 0 :(得分:2)

这里的问题是您将Google Maps version two个对象与Version 3混合在一起。在initialize_google_map函数中,您正在创建并返回GMap2对象(版本2对象)。然后,您将此对象传递给google.maps.Marker对象构造函数(版本3对象)。

您只需修改initialize_google_map函数即可实例化google.maps.Map对象。

答案 1 :(得分:0)

事件在函数之前生成且无法识别,您更改此代码:

$(document).ready(function() {      
     google.maps.event.addListener(map, "click", function(evt) {
            alert("got click event");
            marker.setPosition(evt.latLng);
        });
});

代码:

$(window).load(function(){   
    google.maps.event.addListener(map, "click", function(evt) {
            alert("got click event");
            marker.setPosition(evt.latLng);
        });
});