2011-05-03 39 views
2

我試圖將Google地圖添加到我的某個頁面。將服務器端經度/緯度值添加到Google地圖javascript

在我的代碼隱藏,我有地圖中心點和經度/緯度的數組,我想映射:

protected void Page_Load(object sender, EventArgs e) 
{ 
    Point center = new Point { latitude = 28.42693F, longitude = -81.4673F }; 

    List<Point> points = new List<Point>(); 
    points.Add(new Point { latitude = 28.43039F, longitude = -81.47186F }); 
    points.Add(new Point { latitude = 28.36906F, longitude = -81.56063F }); 

    Point[] pointArray = points.ToArray(); 
} 


public class Point 
{ 
    public float latitude; 
    public float longitude; 
} 

在我的網頁,我有這個JavaScript:

<script type="text/javascript"> 

    function initialize() { 
     if (GBrowserIsCompatible()) { 
      var map = new GMap2(document.getElementById("map_canvas")); 
      map.setCenter(new GLatLng(28.42693, -81.4673), 13); 
      //map.setUIToDefault(); 

      var blueIcon = new GIcon(G_DEFAULT_ICON); 
      blueIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png"; 
      markerOptions = { icon: blueIcon }; 


      var point = new GLatLng(28.43039, -81.47186); 
      map.addOverlay(new GMarker(point, markerOptions)); 

      point = new GLatLng(28.36906, -81.56063); 
      map.addOverlay(new GMarker(point, markerOptions)); 
     } 
    } 

</script> 

這些值現在硬編碼到javascript測試中,但我需要從代碼隱藏中獲取動態值。我怎樣才能做到這一點?

回答

0

一種快速和骯髒的方法可能是在您的代碼隱藏中創建一個字符串,以創建緯度/經度值的JavaScript數組。然後,您可以在.ASPX中添加一個並將其設置爲您的字符串值。或者創建一個你的觀點的JSON表示。它適用於小型一次性場景。因此,您的JavaScript可能會看起來像這樣:

<script type="text/javascript"> 

    function initialize() { 
     if (GBrowserIsCompatible()) { 
      var map = new GMap2(document.getElementById("map_canvas")); 
      <asp:Literal id="litMapCenter" runat="server"/> 
      //map.setUIToDefault(); 

      var blueIcon = new GIcon(G_DEFAULT_ICON); 
      blueIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png"; 
      markerOptions = { icon: blueIcon }; 

      <asp:Literal id="litMapPoints" runat="server"/> 
     } 
    } 

</script> 

在您的代碼隱藏中,然後使用適當的JavaScript設置litMapPoints和litMapCenter。

0

您可以使用這樣的事情在後面的代碼

ClientScript.RegisterStartupScript(this.getType(), "whateveryourkeyis", string.Format("longitude={0};", pointArray[0].longitude), true); 

這樣,您將只需創建一個名爲「經度」 JScript的變量,並與您的.NET代碼值初始化。

(這是寫在飛行中,如果有錯誤,請原諒我:-))

相關問題