2015-01-15 152 views
0

我有一個使用谷歌地圖API顯示郵編的問題。 但是,它給出了一個錯誤:在line谷歌地圖地理編碼 - offsetWidth

未處理的異常...,列...在https://maps.gstatic.com/maps-api-v3/api/js/19/6/main.js

0x800a138f - JavaScript的運行時錯誤:未定義或空引用

無法獲取財產 'offsetWidth'

你能給我一些指導嗎?

代碼文件:

public string location = string.Empty; 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     using (OleDbConnection conn = new OleDbConnection()) 
     { 
      String connection = System.Configuration.ConfigurationManager.ConnectionStrings["google_string"].ConnectionString; 

      conn.ConnectionString = connection; 
      conn.Open(); 

      String sql = "select * from tbl_Post"; 
      OleDbCommand cmd = new OleDbCommand(sql,conn); 
      var rdr = cmd.ExecuteReader(); 
      rdr.Read(); 

      if(!string.IsNullOrEmpty(rdr["location"].ToString())) 
      { 

       location = rdr["location"].ToString(); 
      } 

     } 
    } 
} 

}

asp文件:

<div> 
     <%--map canvas--%> 
     <style type="text/css"> 
      html, body, #map-canvas { 
       height: 100%; 
       margin: 0; 
       padding: 0; 
      } 
     </style> 


     <script type="text/javascript" 
      src="https://maps.googleapis.com/maps/api/js?key=...."> 

     </script> 

     <script type="text/javascript"> 
      var geocoder; 
      var map; 

      function initialize() { 
       geocoder = new google.maps.Geocoder(); 

       var latlng; 
       var mapOptions = { 
        //street level 

        center: new google.maps.LatLng(-34.397, 150.644), 
        zoom: 18, 

       } 


       map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); 

       //load post code address (CALLING FUNCTION) 
       codeAddress(); 
      } 


      google.maps.event.addDomListener(window, "load", initialize); 

      function codeAddress() { 


       geocoder.geocode({ 'address': '<%= location%>' }, function (results, status) { 
        if (status == google.maps.GeocoderStatus.OK) { 
         map.setCenter(results[0].geometry.location); 

         var marker = new google.maps.Marker({ 
          map: map, 
          position: results[0].geometry.location 
         }); 
        } else { 
         alert("Geocode was not succesfull for the following reason" + status); 
        } 
       }); 
      } 
     </script> 

    </div> 

回答

2

這個問題通常是由於javascript運行之前沒有被呈現在地圖div那需要訪問它。

你幾乎就在那裏,因爲你沒有id="map-canvas"元素。所以給你的div一個id,然後它應該按預期工作。

<div id="map-canvas"></div> 
+0

這是絕對正確的,我忘了把這一行。現在它正在工作。 – serb 2015-01-16 17:47:13

+0

非常感謝。 – serb 2015-01-16 17:49:08

+0

非常歡迎您!很高興我能幫上忙 – Izzy 2015-01-16 21:20:46