2010-11-16 58 views
1

我是新的谷歌地圖API。我花了一些樣品從手動,並試圖去改變它,我需要的方式,所以這裏是我想做的事: 這是谷歌的例子映射手動Noob問題:如何獲取信息,如果谷歌地圖加載(初始化)

var geocoder; 
    var map; 
    function initialize() { 
    geocoder = new google.maps.Geocoder(); 
    var latlng = new google.maps.LatLng(40.714353, -74.005973); 
    var myOptions = { 
     zoom: 10, 
     center: latlng, 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    } 
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); 
    } 

    function codeAddress() { 
    var address = document.getElementById("address").value; 
    geocoder.geocode({ 'address': address}, 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 successful for the following reason: " + status); 
     } 
    }); 
    } 

我已經改變codeAddress功能小並試圖把它在頁面加載這樣的:

function codeAddress(address) { 
     //var address = document.getElementById("address").value; 
     geocoder.geocode({ 'address': address}, 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 successful for the following reason: " + status); 
      } 
     }); 
     } 
codeAddress("Some Address"); 

但它給我一個JavaScript錯誤「地理編碼器未定義」。我如何讓腳本等到地圖加載後再運行codeAddress函數?我不想在初始化期間路由我的地址。

我希望這是明確的 預先感謝您。

+0

我很抱歉這個愚蠢的問題。我有地址字符串的問題,所以我糾正它,並得到腳本工作。無論如何感謝 – KoKo 2010-11-17 16:49:21

回答

2

的問題是,你定義它後直接調用codeAddress(因此這是initialise()方法運行之前。

因此你需要一些觸發後運行此。一個快速和骯髒的方式做這是設置此爲人體的onload事件;這將等到所有資源(包括圖片)已經滿載,但可能不會是太大的問題因爲地圖是一個形象,以及

或者。 ,大多數JS框架將爲您提供非常方便的方法來在頁面生命週期的各個點觸發您的處理程序。如果您使用一個f這些,你可能希望調查可用的選項並選擇最好的選項,這取決於許多因素。

很重要的是,不要忘記,在致電codeAddress()之前,您必須致電initialise()

+0

我在body中調用和codeAddress。如果我在主體或甚至結束時移動初始化。它給了我Geocode未成功的警報。 – KoKo 2010-11-16 12:26:02

+0

@KoKo - 'alert'是一種改進,因爲它意味着'geocoder'變量已被填充並被調用。因此你原來的問題已經解決了。 – 2010-11-16 16:43:17