2012-08-03 25 views
3

我試圖在我的頁面中的Google地圖元素上顯示地址作爲標記。未定義不是函數,Google地理位置

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=my_key&sensor=true&callback=initialize"></script> 
<script language="javascript" type="text/javascript"> 
    navigator.geolocation.getCurrentPosition(foundLocation, noLocation); 
    var latitude; 
    var longitude; 
    var map; 
    function foundLocation(position) { 
     latitude = position.coords.latitude; 
     longitude = position.coords.longitude; 
    } 
    function noLocation() { 
     //Do something here in the case that no location is found, or user denies access 
    } 
    function initialize() { 
     var mapOptions = { 
      zoom: 8, 
      center: new google.maps.LatLng(latitude, longitude), 
      mapTypeId: google.maps.MapTypeId.ROADMAP 
     } 
     map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); 
     //setMarkers(); 
    } 
    function addMarker(location) { 
     var marker = new google.maps.Marker({ 
      position: location, 
      map: map 
     }); 
     markersArray.push(marker); 
    } 
</script> 


<span id="ctl00_ContentPlaceHolder1_lblGeneratedScript"><script language="javascript" type="text/javascript"> 
    var geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({ 'address': "123 Test Dr."}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      addMarker(results[0].geometry.location); 
     } else { 
      alert("Geocode failed! Reason: " + status); 
     } 
    }); 
</script> 
</span> 

但是,在這條線

var geocoder = new google.maps.Geocoder(); 

我得到的未捕獲的類型錯誤「未定義是不是一個函數」。

我在我的代碼選擇中省略了我的api鍵,並且改變了我用來測試的地址。 (我的家庭地址)

另外,我正在使用ASP.NET在span標記中生成腳本。

回答

4

在API加載完成之前,您無法構造Geocoder對象。在您的initialize方法中或之後調用它。

+0

非常感謝,這工作像一個魅力! – 2012-08-03 16:11:57