2010-12-20 13 views
3

Google Maps APIを使用して、ユーザーが提供する場所を取得しようとしています。これを行うには、「クリック」イベントに基づいて移動するマーカーを設定します。Google Maps API google.maps.eventが定義されていません

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コンソール(Google Chromeは)この言葉::のようなコードがある
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

ここで問題となるのは、Google Maps version twoオブジェクトをVersion 3と混在させることです。 initialize_google_map関数では、GMap2オブジェクト(バージョン2オブジェクト)を作成して返します。このオブジェクトをgoogle.maps.Markerオブジェクトコンストラクタ(バージョン3オブジェクト)に渡します。

google.maps.Mapオブジェクトをインスタンス化するには、initialize_google_map関数を変更するだけです。

+0

素晴らしい、ありがとうございました!私はそれが見つからないとは信じられません。 –

+0

@ john-dorn問題なし:) – RedBlueThing

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); 
     }); 
}); 
関連する問題