获取'未捕获的TypeError:无法读取属性'地理编码'未定义'错误

时间:2015-10-26 06:13:16

标签: javascript google-maps

当我运行以下代码时,我已经从this回答,我在浏览器的控制台中出现Uncaught TypeError: Cannot read property 'geocode' of undefined错误,为什么会发生这种情况,因为这里的正文加载initialize必须调用函数,而不是调用initialize函数,codeLatLng(lat, lng)函数首先调用。

<!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> 

1 个答案:

答案 0 :(得分:8)

在初始化Geocoder实例之前,无需等待onload-event。您可以同步加载maps-API,因此API(包括container.RegisterType<MyCustomService<>>(new TransientLifetimeManager()); )在加载API后立即可用。

问题:当地理位置运行得太快,并且google.maps.Geocoder的回调将在onload-event之前执行时,地理编码器为navigator.geolocation.getCurrentPosition

替换此行:

undefined

这一行:

var geocoder;