0
var geocoder = new google.maps.Geocoder();
var address = document.getElementById('sub_id').value;
var address1=document.getElementById('sub').value;
geocoder.geocode({ 'address': address }, function (results, status) {

    if (status == google.maps.GeocoderStatus.OK) {
        console.log('Inside status');
        var latitude = results[0].geometry.location.lat();
         longitude = results[0].geometry.location.lng();

    }


});
console.log(latitude);

When I am trying to print the above latitude and longitude on outside the function, the value is undefined.

How can I solve this issue?

Turnip
  • 35,836
  • 15
  • 89
  • 111
lekshmi
  • 101
  • 3
  • That's because latitude is declared inside your function, if you want it to have scope outside of the function you would need to declare it above the call to geocoder.geocode.Also, geocoder.geocode looks like it is an async function which means you would need to console.log latitude or what ever programming logic you need inside the if statement contained inside the callback function of geocoder.geocode – Ryan Wilson Mar 26 '18 at 12:34
  • Of course it gets `undefined`. It's the expected result. Declare the variables outside the function and asign them values inside the function. Then you should see the values when logging. – Ionut Necula Mar 26 '18 at 12:34
  • That won't work @Ionut as the values are retrieved asynchronously – Dan Mar 26 '18 at 12:36
  • @DanPantry, of course, if the function is async then he should treat what he wants inside the function or use a `promise` or something. – Ionut Necula Mar 26 '18 at 12:37
  • create the variable in global scope and assign the latitude value to the global variable. Later access that global variable for further operation. – Suresh Ponnukalai Mar 26 '18 at 12:37
  • I tried that too, but then also it displays undefined – lekshmi Mar 26 '18 at 12:38
  • That won't work @SureshPonnukalai as I just mentioned to Ionut. Please see the answer that Bengi has marked this question as a duplicate of. – Dan Mar 26 '18 at 12:38
  • Your log runs before the function execution ends, if the functions it's asynchronous. So you're actually asigning the value to the variable after the `console.log(latitude)` – Ionut Necula Mar 26 '18 at 12:38

0 Answers0