1

I'm using google map geocoding to get latitude,longitude value from address.Here is my code,

var latd;
var lond;
geocoder.geocode({ 'address': address }, function (results, status) {

    if (status == google.maps.GeocoderStatus.OK) {
       console.log(place);
       var latd = results[0].geometry.location.lat();
       var lond = results[0].geometry.location.lng();
     }
    console.log(latd);
});
//console.log(latd);

When access the variable latd outside function, its value seems undefined. What's the issue with the above code?

Update1:

    getlatlang(address);
    console.log(latd);//Not defined


function getlatlang(address)
{
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': address }, function (results, status) {

        if (status == google.maps.GeocoderStatus.OK) {
            //console.log(place);
            latd = results[0].geometry.location.lat();
            lond = results[0].geometry.location.lng();
             return latd,lond;
             }

     });
}
msanford
  • 11,803
  • 11
  • 66
  • 93
usertest
  • 399
  • 2
  • 14
  • 31

2 Answers2

1

First, because the variable you try to access into your condition will be accessible only into the context if. The variable your redeclared into if is new variable.

if (status == google.maps.GeocoderStatus.OK) {
   console.log(place);
   var latd = results[0].geometry.location.lat();
   var lond = results[0].geometry.location.lng();
   console.log(latd, lond)
}

You can change with this:

var latd;
var lond;
geocoder.geocode({ 'address': address }, function (results, status) {

   if (status == google.maps.GeocoderStatus.OK) {
      console.log(place);
      latd = results[0].geometry.location.lat();
      lond = results[0].geometry.location.lng();
   }
   console.log(latd);
});

Update

geocoder.geocode is an async function. You have to wait until it's done. Your variable after the geocoder.geocod is executed even if the geocoder hasn't yet finished to be executed. So your variable is always undefined, because you create a variable with undefined value.

Note: All your action should be into the callback function, of geocoder, otherwise, it will always undefined.

Radonirina Maminiaina
  • 6,958
  • 4
  • 33
  • 60
1

If you want to have access to lat, long outside the function simply assign them and do not create them inside. You can read more about JavaScript Scope

    var latd;
    var lond;
     geocoder.geocode({ 'address': address }, function (results, status) {

        if (status == google.maps.GeocoderStatus.OK) {
            console.log(place);
            latd = results[0].geometry.location.lat();
            lond = results[0].geometry.location.lng();
         }
      console.log(latd);
     });
     //console.log(latd);
Denis Potapov
  • 664
  • 2
  • 12
  • 18