D
D
Dima Pautov2015-11-17 14:18:40
JavaScript
Dima Pautov, 2015-11-17 14:18:40

Why is the value not written to the variable?

Good afternoon everyone. Why can't I write the coordinate value to the position variable declared at the very beginning of the geocode function??

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

  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status === google.maps.GeocoderStatus.OK) {
      position = results[0].geometry.location;
console.log(position);// Все ок, координаты записаны, карта показалась!
      map.panTo(position);
    } else {
      alert('Адрес указан не верно: ' + status);
    }
  });
console.log(position); // А тут они undefined, разве я не записал значение в переменную?

Why is that?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yaroslav Lyzlov, 2015-11-17
@bootd

Because geocoder.geocode is an asynchronous function, and when you output position at the end, the value isn't there yet. Go read about the basics of JS, otherwise you will ask such questions every day.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question