Google Geocoder Asynchronous Issue

为君一笑 提交于 2019-12-07 02:48:27

This is because you check the value of hasResult before you get the results from the server. This happens, because the request is asynchrounous. You should use callbacks instead.

Edit:

Try this (this is only a mockup and is not tested, change it to improve readability, pass successOrFailure as a parameter/callback etc.):

var hasResult = false;            

var successOrFailure = function(hasResult){
    if (hasResult == true) {
        alert('Success');
    } else {
        alert('Fail');
    }
};

geocoder.geocode({ "address": address }, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        $.ajax({
            url: "URL",
            type: "POST",
            dataType: "json",
            data: results
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                        if (result.Valid) {
                            hasResult = false;
                            successOrFailure(hasResult);
                            //Some other code, works perfect                            
                        } else {
                            geocoder.geocode({ "address": result.ValidRequest }, function (resultsNew, statusNew) {
                                if (statusNew == google.maps.GeocoderStatus.OK) {
                                    hasResult = false;
                                    successOrFailure(hasResult); 
                                    //Some other code, works perfect
                                }
                            });
                        }
                    });
                });
            }
        });
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!