-1

I have some issues defining position inside my geocode function. I do get the right result in my function, but i can't use it outside the function.

var position;

var geocoder = new google.maps.Geocoder();

geocoder.geocode({
  'address': row.Address + ' ' + row.Postal_Code + ' ' + row.City + ' ,' + row.Country
}, function(results, status) {
  if(status == google.maps.GeocoderStatus.OK) {
    position = results[0].geometry.location; // console.log(position) // correct result
  }
});

console.log(result); // Undefined

HassanUsman
  • 1,787
  • 1
  • 20
  • 38
andershagbard
  • 1,116
  • 2
  • 14
  • 38

2 Answers2

1

Unless you don't run your function in geocode the value is not assigned to position variable.

var position;
function forPosition(results, status) {
    if(status == google.maps.GeocoderStatus.OK) {
    position = results[0].geometry.location;
}
forPosition();// now position is set to results[0].geometry.location;

You have an anonymous function which should run in order to assign a value to the variable.

Or simply in the example below

var greeting = "Hello";
function func(){
    greeting = "hi"
    alert(greeting)
}
//func() //uncommenting func() will result in alerting two times 'hi'. 
alert(greeting)

After function func is ran it sets greeting variable to 'hi' and alerts the variable inside the function, then alert outside the scope of function will alert the greeting variable once more. Unless the function runs greeting is always set to "Hello".

RegarBoy
  • 3,228
  • 1
  • 23
  • 44
-1

You have assigned a position variable in your callback function and now you are trying to output result variable to console. This variable has never been declared or assigned. It should definitely return undefined.

It should work:

console.log(position);

Update:
OK, now, a little correction - google.maps.Geocoder is an asynchronous method. The OP did not mention it anywhere in the post - I had to find this library, download it, research it's API and learn it myself.
In my opinion, all users do not obligatory know every third-party library and, in this case, I was right - this code would output undefined even if the method was synchronous as it still outputs an undefined variable.

Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101
  • I'm defining position inside my function, and inside my function, it has the correct result. – andershagbard Aug 10 '15 at 11:14
  • @MatíasFidemraizer Ok. I am not sure that `console.log(position)` should work. I am sure that `result` variable has never been declared or assigned. How is it supposed to make a proper output? – Yeldar Kurmangaliyev Aug 10 '15 at 11:16
  • What Yeldar means is that you're using `console.log(result);` and not `console.log(position);`. But that won't work either (see my comment about it being an asynchronous function). – Andy Aug 10 '15 at 11:16