2015-10-26 87 views
2

當我運行下面的代碼,這是我從this得到的答案,我得到Uncaught TypeError: Cannot read property 'geocode' of undefined錯誤在瀏覽器的控制檯,爲什麼它發生,因爲在身體在這裏加載initialize函數必須被調用,而不是調用initialize函數,這裏codeLatLng(lat, lng)首先調用。獲取'Uncaught TypeError:無法讀取屬性'未定義的'geocode'錯誤

<!DOCTYPE html> 
<html> 
<head> 
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
<title>Reverse Geocoding</title> 

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript"> 
    var geocoder; 

    if (navigator.geolocation) { 
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction); 
} 
//Get the latitude and the longitude; 
function successFunction(position) { 
    var lat = position.coords.latitude; 
    var lng = position.coords.longitude; 
    codeLatLng(lat, lng) 
} 

function errorFunction(){ 
    alert("Geocoder failed"); 
} 

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



    } 

    function codeLatLng(lat, lng) { 

    var latlng = new google.maps.LatLng(lat, lng); 
    geocoder.geocode({'latLng': latlng}, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
     console.log(results) 
     if (results[1]) { 
     //formatted address 
     alert(results[0].formatted_address) 
     //find country name 
      for (var i=0; i<results[0].address_components.length; i++) { 
      for (var b=0;b<results[0].address_components[i].types.length;b++) { 

      //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate 
       if (results[0].address_components[i].types[b] == "administrative_area_level_1") { 
        //this is the object you are looking for 
        city= results[0].address_components[i]; 
        break; 
       } 
      } 
     } 
     //city data 
     alert(city.short_name + " " + city.long_name) 


     } else { 
      alert("No results found"); 
     } 
     } else { 
     alert("Geocoder failed due to: " + status); 
     } 
    }); 
    } 
</script> 
</head> 
<body onload="initialize()"> 

</body> 
</html> 
+0

這運行正常,我在Safari ..你想它哪種瀏覽器? –

+0

好吧,我也會在Safari瀏覽器中檢查它,感謝您的評論,我在Chrome中運行它 –

回答

4

在初始化Geocoder實例之前,不需要等待onload事件。您可以同步加載maps-API,因此在加載API後立即可以使用API​​(包括google.maps.Geocoder)。

問題:當地理位置運行速度過快,並且navigator.geolocation.getCurrentPosition的回調將在onload事件之前執行時,geocoder是undefined

替換此行:

var geocoder; 

這一行:

var geocoder = new google.maps.Geocoder(); 
相關問題