Czemu funkcja nic nie zwraca za pierwszym razem ?

0

Mam taka funkcje, która powinna działać po naciśnięciu guzka na mapie google

alert('1 - przed get addres');
public_address = getAddressName(coord.latLng);
alert('6 - to co zwrocila f: '+public_address);

function getAddressName(latlng) {
    alert('2 - funkcja get adres'); 
    geocoder.geocode({'latLng': latlng}, function(results, status) { 
    alert('3 - pobrane dane o adresie');
    rs = results[0].formatted_address;
    alert('4 - adres: ' + rs);
					
    return rs;
    alert('5a - zwrot: ' + rs);
});
alert('5 - zwrot: ' + rs);
return rs;
}

Chodzi o to że pojawia się alert:
1,2,3,4 i na tym działanie się kończy nie wyświetla mi alertu 6
jak zakomentuje "RS" miedzy alertem 4 i 5a również mam tylko wyświetlone pierwsze 4 alerty i funkcja się urywa.
Dopiero ponowne kliknięcie na funkcję sprawia, że pojawia się alert 6?

Ma ktoś jakiś pomysł ?

0

1.Formatowanie kodu!

alert('1 - przed get addres');
public_address = getAddressName(coord.latLng);
alert('6 - to co zwrocila f: ' + public_address);

function getAddressName(latlng) {
    alert('2 - funkcja get adres');
    geocoder.geocode({
        'latLng': latlng
    }, function (results, status) {
        alert('3 - pobrane dane o adresie');
        rs = results[0].formatted_address;
        alert('4 - adres: ' + rs);

        return rs;
        alert('5a - zwrot: ' + rs);
    });
    alert('5 - zwrot: ' + rs);
    return rs;
}

2.Jak zgaduję, jest to powiązane z wysyłaniem danych asynchronicznie; spróbuj tak:

getAddressName(coord.latLng, function(data)
{
 public_address = data;
});

function getAddressName(latlng, callback) {
    geocoder.geocode({
        'latLng': latlng
    }, function (results, status) {
        callback(results[0].formatted_address);
    });
}

1 użytkowników online, w tym zalogowanych: 0, gości: 1