javascript 获取“未捕获的类型错误:无法读取未定义”错误的属性“地理编码”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33339494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:22:19  来源:igfitidea点击:

Getting 'Uncaught TypeError: Cannot read property 'geocode' of undefined ' error

javascriptgoogle-maps

提问by Praveen Rawat

When i am running the following code, which i have taken from thisanswer, i am getting Uncaught TypeError: Cannot read property 'geocode' of undefinederror in browser's console, why its happening because on the body load here initializefunction has to be called, and instead of calling initializefunction here codeLatLng(lat, lng)is calling first.

当我运行以下代码(我从这个答案中获取)时,我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> 

回答by Dr.Molle

There is no need to wait for the onload-event until you initialize the Geocoder-instance. You load the maps-API synchronously, so the API(including google.maps.Geocoder) is available immediately after loading the API.

在初始化 Geocoder-instance 之前,无需等待 onload-event。您同步加载 maps-API,因此google.maps.Geocoder加载 API 后API(包括)立即可用。

The issue: when geolocation runs too fast, and the callback of navigator.geolocation.getCurrentPositionwill be executed before the onload-event, geocoder is undefined.

问题:当 geolocation 运行太快,并且 的回调navigator.geolocation.getCurrentPosition将在 onload-event 之前执行,geocoder 是undefined.

Replace this line:

替换这一行:

var geocoder;

with this line:

用这一行:

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