最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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

<!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=""></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_ponents.length; i++) {
            for (var b=0;b<results[0].address_ponents[i].types.length;b++) {

            //there are different types that might hold a city admin_area_lvl_1 usually does in e cases looking for sublocality type will be more appropriate
                if (results[0].address_ponents[i].types[b] == "administrative_area_level_1") {
                    //this is the object you are looking for
                    city= results[0].address_ponents[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> 

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

<!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./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_ponents.length; i++) {
            for (var b=0;b<results[0].address_ponents[i].types.length;b++) {

            //there are different types that might hold a city admin_area_lvl_1 usually does in e cases looking for sublocality type will be more appropriate
                if (results[0].address_ponents[i].types[b] == "administrative_area_level_1") {
                    //this is the object you are looking for
                    city= results[0].address_ponents[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> 
Share Improve this question edited May 23, 2017 at 12:00 CommunityBot 11 silver badge asked Oct 26, 2015 at 6:13 Praveen RawatPraveen Rawat 7342 gold badges12 silver badges30 bronze badges 2
  • this runs fine for me in Safari.. Which browser are you trying it on? – s_curry_s Commented Oct 26, 2015 at 6:22
  • ok i will also check it in safari thanks for your ment, i was running it in chrome – Praveen Rawat Commented Oct 26, 2015 at 6:23
Add a ment  | 

1 Answer 1

Reset to default 11

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.

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

Replace this line:

var geocoder;

with this line:

var geocoder = new google.maps.Geocoder();
发布评论

评论列表(0)

  1. 暂无评论