Search code examples
javascriptphpfunctiongoogle-mapses6-promise

javascript function returning undefined but working fine on alert


i am using google map api in which there is function where i am passing address and the function returns the latitude and longitude but in this code function returning me undefined , but when i am using alert instead of return it's working fine, please tell me where i am wrong in this code. i have same problem in past with ajax code but where i use async=false .

<script>
  function GetLocation(address) {
            var geocoder = new google.maps.Geocoder();
           
            geocoder.geocode({ 'address': address }, function (results, status) {
          
        
                if (status == google.maps.GeocoderStatus.OK) {
                    var latitude = results[0].geometry.location.lat();
                    var longitude = results[0].geometry.location.lng();
          return longitude;
          //          alert("Latitude: " + latitude + "\nLongitude: " + longitude);
          // return latitude;
           
                } else {
                  
            return "Request failed.";
                } 
        
            });

        };  
 
 
 var abc = GetLocation(address);

alert(abc);

</script>


Solution

  • Your geocode() is an asynchronous call and you can't return something from it. So you need to continue your logic which is depend on results in the callback function.

    Or you need to use Promise, and change some logic to achieve the result. But again with Promises you can't return anything from it. |

    In this code you create an return a Promise from the function. Promise will take 2 functions, one if everything is OK, and the second, if something is wrong. If everything is OK, you call it with your parameter. On Promise you can call .then() function and pass into it 2 functions: first will be passed as your resolve function, the second as reject function. So in this case, when you call resolve, it passes the parameter to the first function of .then() and you get it there.

    function GetLocation(address) {
      return new Promise(function(resolve, reject) { 
          var geocoder = new google.maps.Geocoder();
          geocoder.geocode({ 'address': address }, function (results, status) {
                      
             if (status == google.maps.GeocoderStatus.OK) {
                 var latitude = results[0].geometry.location.lat();
                 var longitude = results[0].geometry.location.lng();
                 resolve(longitude);
             } else { 
                 reject("Request failed.");
             }         
          });
       });    
    };
                 
    var address = 'yourAddress';
    GetLocation(address).then(longitude => alert(longitude));

    Basic example with Promises

    new Promise((resolve, reject) =>{
      var a = true; // < Here `a` is true, so resolved function is called in `then`
      if(a){
        resolve(a); 
      } else {
        reject('A is not True !');
      }  
    }).then(val => alert(val));
    
    
    new Promise((resolve, reject) =>{
      var a = false; // < Here `a` is false, so rejected function is called `then`
      if(a){
        resolve(a); 
      } else {
        reject('A is not True !');
      }  
    }).then(val => alert(val), err => alert(err));