0

I wonder why this does not work, it perfectly logs Object {lat: 52.132633, lng: 5.291265999999999}. But only the console.log() inside the done() function works. To other one does not work, while I return that exact variable...

function getLatLng() {
    var LatLng;
    $.ajax({
        url: 'https://maps.googleapis.com/maps/api/geocode/json?address=germany&sensor=false',
        type: 'GET',
        dataType: 'json',
    })
    .done(function(data) {
        LatLng = data.results[0];
        console.log(LatLng);
    })
    return LatLng;
}

console.log(getLatLng());

I need some workaround so that I can make the initMap() function work with my lattitude and longitude variables:

function getLatLng() {
    var LatLng;
    $.ajax({
        url: 'https://maps.googleapis.com/maps/api/geocode/json?address=germany&sensor=false',
        type: 'GET',
        dataType: 'json',
    })
    .done(function(data) {
        LatLng = data.results[0];
        console.log(LatLng);
    })
    return LatLng;
}

console.log(getLatLng()); // undefined

  function initMap() {

    var styledMapType = new google.maps.StyledMapType(
        [],
        {name: 'Styled Map'});

    var map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: latVal, lng: lngVal}, // error >>> undefined
      zoom: 11,
      mapTypeControlOptions: {
        mapTypeIds: ['roadmap', 'satellite', 'hybrid', 'terrain',
                'styled_map']
      }
    });

    map.mapTypes.set('styled_map', styledMapType);
    map.setMapTypeId('styled_map');
  }
Derk Jan Speelman
  • 11,291
  • 4
  • 29
  • 45

1 Answers1

1

This is because the call to the google api is asynchronous. This means the outer console log is executed while the response from google is still pending.

You could write it like this:

function getLatLng() {
    return $.ajax({
        url: 'https://maps.googleapis.com/maps/api/geocode/json?address=germany&sensor=false',
        type: 'GET',
        dataType: 'json',
    });
}

getLatLng().done(function(data) {
    var latlng = data.results[0];
    console.log(latlng);
    //...further processing
});

If you need access to latlng outside the done function you could rewrite as so:

function getLatLngPromise() {
    return new Promise(function(resolve) { 
        $.ajax({
            url: 'https://maps.googleapis.com/maps/api/geocode/json?address=germany&sensor=false',
            type: 'GET',
            dataType: 'json',
        }).done(function(data) {
            resolve(data);
        });
    });
}

async function getLatLng() {
    var data = await getLatLngPromise();
    return data[0];
}

var latlng = getLatLng();
console.log(latlng);

Or you could parametrize the initMap with a latlng parameter and move the initMap call to the done function of my first example. (pastebin.com/VpSUma9R)

Derk Jan Speelman
  • 11,291
  • 4
  • 29
  • 45