2010-12-22 45 views
5

我正在使用google maps API並複製了這些示例,並且結束了一個名爲「初始化」的函數,該函數從onload正文中調用。Google Maps API 3如何調用初始化而不將它放入Body onload

我在幾個不同的用戶控件中使用地圖,這些用戶控件位於內容佔位符中,因此主體標籤位於主頁面中。

有沒有一種方法直接在用戶控件中調用初始化,而不必在主頁上放置onload? 理想情況下,我希望我的用戶控件是一個獨立控件,我可以插入頁面而不嘗試訪問主頁面主體onload。

我已經嘗試從用戶控件的頁面加載(通過添加啓動腳本)調用Initialize函數,但不顯示地圖。

有什麼建議嗎?

我的代碼:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">/script> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 
<script type="text/javascript"> 
var map; 
var geocoder; 
function initialize() { 
    geocoder = new google.maps.Geocoder(); 
    var latlng = new google.maps.LatLng(51.8052184317649, -4.965819906250006); 
    var myOptions = { 
     zoom: 8, 
     center: latlng, 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    }; 
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 

    $.ajax({ 
     type: "POST", 
     url: "/GoogleMapsService.asmx/GetPointers", 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     beforeSend: function() { 
      $(".loadingData").html("<p>Loading data..</p>"); 
     }, 
     complete: function() { 
      $(".loadingData").html(""); 
     }, 
     cache: true, 
     success: mapPoints, 
     error: onError 
    }); 
} 
function onError(xhr, ajaxOptions, thrownError) { 
    alert(xhr.status); 
    alert(xhr.responseText); 
} 
function mapPoints(response) { 

    if (response.d != null) { 
     if (response.d.length > 0) { 
      for (var i = 0; i < response.d.length; i++) { 

       plotOnMap(response.d[i].Id, response.d[i].Name, 
        response.d[i].Lat, response.d[i].Long, 
        response.d[i].ShortDesc) 

      } 
     } 

    } 
} 

和我的測試母版頁:

<body onload="initialize()"> 
<form runat="server"> 
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager> 
<asp:ContentPlaceHolder ID="MainContent" runat="server"> 
</asp:ContentPlaceHolder> 
</form> 
</body> 
+0

你能幫助這個鏈接嗎?http://stackoverflow.com/questions/29792518/why-didnt-work-my-classic-asp-source-code – pcs 2015-04-22 12:49:58

回答

2

感謝您的回答,但我終於這樣做了:

<script type="text/javascript"> 
    window.onload = function() { 
     initialize(); 
    } 
</script> 
1

這是我要做的事:(這個腳本可以在用戶控件使用)

<script type="text/javascript"> 

      $(document).ready(function() { 
      if ($('#map_canvas').length != 0) { 
      //google map stuff here 
      } 
     }); 
    </script>