-2

So basically I am trying to pass in a location using google Geocoder and be able to capture the returned longitude to a variable 'x' when invoked. However when i am logging it on the console, it is returning 'undefined', but from the onSuccess() function it logs the longitude. Any help would be great thanks.

function onSuccess(position) {
  getLocationData(position, function(locationData){
    y = locationData;
    console.log("inside onSuccess Function: "+y);
  return y;
      });
    }

function getLocationData(position, callback) {
 geocoder = new google.maps.Geocoder();

 if( geocoder ) {
  geocoder.geocode({ 'address': position }, function (results, status) {
   if( status == google.maps.GeocoderStatus.OK ) {
   callback(results[0].geometry.location.lng());
     }
   });
  }
 }
var x = onSuccess('Billings,MT');
console.log("Yayyy: "+x);

1 Answers1

0

You can not do that, but you can use callback method

function onSuccess(position) {
  getLocationData(position, function(locationData){
    y = locationData;
    console.log("inside onSuccess Function: "+y);
  return y;
      });
    }

function getLocationData(position, callback) {
 geocoder = new google.maps.Geocoder();

 if( geocoder ) {
  geocoder.geocode({ 'address': position }, function (results, status) {
   if( status == google.maps.GeocoderStatus.OK ) {
   callback(results[0].geometry.location.lng());
     }
   });
  }
 }
var x ;
onSuccess('Billings,MT', function(callBackData){
x = callBackData
    console.log("Yayyy: "+x);
  });
Nitin Daddikar
  • 335
  • 5
  • 12