2010-12-22 66 views
0
$(function(){ 

    //Location was "set". Perform actions. 
    $("#geocodesubmit").click(function(){ 
     var geocoder = new google.maps.Geocoder(); 
     geocoder.geocode({ 'address': address}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      $("#map_canvas").show(); 
      var myOptions = { 
       zoom: 15, 
       center: results[0].geometry.location, 
       mapTypeControl:false, 
       mapTypeId: google.maps.MapTypeId.ROADMAP, 
       scrollwheel:false, 
      }; 
      var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
      var marker = new google.maps.Marker({ 
        map: map, 
        position: results[0].geometry.location, 
        draggable:true 
      }); 
     } 
     }); 

     return false; 
    }); 

    //Marker was dragged. 
    google.maps.event.addListener(marker,"dragend",function(){ 
      alert('hi'); 
    }); 
}); 

正如你在這裏看到的,當用戶點擊一個按鈕時,我生成一個新的Google map和一個新的。但問題是標記沒有被綁定。我的一個javascript變量是undefined,我該怎麼辦?

當這個頁面加載,有一個錯誤:

Uncaught ReferenceError: marker is undefined

我猜這是因爲直到按鈕被點擊才啓動標記。我如何成功綁定市場? (我更喜歡在點擊按鈕後加載地圖,因爲在加載頁面時加載地圖時存在顯示問題,然後隱藏它)

回答

0

addListener調用移入click處理程序。

+0

這弄亂的東西了 – TIMEX 2010-12-22 01:03:30

0

試試這個

$(function() { 
    var marker; 
    //Location was "set". Perform actions. 
    $("#geocodesubmit").click(function() { 
     var geocoder = new google.maps.Geocoder(); 
     geocoder.geocode({ 
      'address': address 
     }, function (results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       $("#map_canvas").show(); 
       var myOptions = { 
        zoom: 15, 
        center: results[0].geometry.location, 
        mapTypeControl: false, 
        mapTypeId: google.maps.MapTypeId.ROADMAP, 
        scrollwheel: false, 
       }; 
       var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
       marker = new google.maps.Marker({ 
        map: map, 
        position: results[0].geometry.location, 
        draggable: true 
       }); 
      } 
     }); 

     return false; 
    }); 
    //Marker was dragged. 
    google.maps.event.addListener(marker, "dragend", function() { 
     alert('hi'); 
    }); 
});