Javascript函数不等待函数完成

时间:2018-11-21 00:38:46

标签: javascript

我正在尝试编写一个地图功能,该功能会添加所有位置标记。但是,我在代码中有一个地方可以调用一个函数,但是js在继续运行代码之前没有等待响应。这是完整的脚本。

有问题的问题在此代码行的getMap()函数内部

TrialLocationAddress = getTrialLocationGeoCode(TrialLocation.Address);

在继续之前,我需要它在这里等待直到正确获得地址为止。我尝试插入await,但随后抛出并报错,说它只是异步功能

<script type="text/javascript">
    var MapID = "googleMap";
    var defaultMapLocation = {
        lat: 40.196409,
        lon: -97.885575,
        zoom: 4.75
    };
    var NewMapOptions;
    var TrialLocations = [
        {
            Name: "Medicine",
            Address: "Address 1, Abington, PA 19046"
        },
        {
            Name: "Boston",
            Address: "Address 2, Waltham, MA 02451"
        }
        ];
    var TrialLocationInfoWindows = [];
    
    function initMap() {

        var gGeoCoder;
        var UserEnteredAddress = '<?php echo ( !empty( $UserEnteredAddress ) ? $UserEnteredAddress : "false"); ?>';
        var MapPosition = new google.maps.LatLng(defaultMapLocation['lat'], defaultMapLocation['lon']);

        if( UserEnteredAddress !== 'false' )
        {
            gGeoCoder = new google.maps.Geocoder();
            if ( gGeoCoder ) {
                gGeoCoder.geocode({
                    'address': UserEnteredAddress
                }, function (results, status)
                {
                    if ( status === google.maps.GeocoderStatus.OK ) {
                        if ( status !== google.maps.GeocoderStatus.ZERO_RESULTS ) {
                            NewMapOptions = {
                                zoom: 7,
                                center: results[0].geometry.location
                            };
                            getMap(NewMapOptions, results[0]);
                        } else {
                            alert("No location results found");
                        }
                    } else {
                        alert("Geocode was not successful for the following reason: " + status);
                    }
                });
            } else {
                alert( "Geocode encountered an error initializing" );
            }
        } else {
            NewMapOptions = {
                zoom: defaultMapLocation['zoom'],
                center: MapPosition
            };
            getMap( NewMapOptions );
        }
    }

    function getMap( NewMap, SearchLocation = false ) {
        var i = 0;
        var map = new google.maps.Map(document.getElementById(MapID), NewMap);
        var TrialLocationAddress;
        
        if( SearchLocation !== false )
        {
            var infowindow = new google.maps.InfoWindow(
                {
                    content: '<b>Your Location:</b> ' + SearchLocation.formatted_address,
                    size: new google.maps.Size(150, 50)
                });
    
            var searchMarker = new google.maps.Marker({
                position: SearchLocation.geometry.location,
                map: map,
                title: SearchLocation.formatted_address,
                icon:{
                    url: "http://maps.google.com/mapfiles/kml/pal2/icon13.png"
                }
            });
           
            google.maps.event.addListener( searchMarker, 'click', function () {
                infowindow.open(map, searchMarker);
            });
        }

        TrialLocations.forEach(function(TrialLocation){
            console.log( TrialLocation.Address );
            TrialLocationAddress = getTrialLocationGeoCode(TrialLocation.Address);
            console.log( "AFTER ADDRESS:" + TrialLocationAddress );
            if( TrialLocationAddress !== false && typeof TrialLocationAddress != 'undefined') {
                console.log("trial location address:" + TrialLocationAddress );
                var TrialLocationMarker = new google.maps.Marker({
                    position: TrialLocationAddress.geometry.location,
                    map: map,
                    title: TrialLocation.Name
                });

                google.maps.event.addListener(TrialLocationMarker, 'click', function (TrialLocation, i) {
                    return function () {
                        var infowindow = new google.maps.InfoWindow(
                            {
                                content: '<b>' + TrialLocation.Name + '</b>',
                                size: new google.maps.Size(150, 50)
                            });
                        infowindow.open(map, TrialLocationMarker);
                    }
                });
            }
        });
    }
    
    function getTrialLocationGeoCode( Address )
    {
        console.log ("init trial geo");
        gGeoCoder = new google.maps.Geocoder();
        if ( gGeoCoder ) {
            gGeoCoder.geocode({
                'address': Address
            }, function (results, status)
            {
                console.log("inside the function for location geo");
                if ( status === google.maps.GeocoderStatus.OK ) {
                    if ( status !== google.maps.GeocoderStatus.ZERO_RESULTS ) {
                            console.log("inside trialgeo" + results[0] );
                            return results[0];
                    } else {
                        console.log("error 1");
                        return false;
                    }
                } else {
                    console.log("error 2");
                    return false;
                }
            });
        } else {
            console.log("error 3");
            return false;
        }
    }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key={APIKEY}&callback=initMap"></script>
<div id="googleMap" style="width: 100%; height:600px;"></div>

<?php
if( array_key_exists( "search", $_POST ) ):
    $UserEnteredAddress = $_POST["search"];
elseif( array_key_exists( "search", $_GET ) ):
    $UserEnteredAddress = $_GET["search"];
else:
    $UserEnteredAddress = "";
endif;
?>

2 个答案:

答案 0 :(得分:1)

您可以通过两种方法解决此问题:

1用for循环替换地图

2添加一个计数器,用于检查回调函数是否已迭代每个元素。

答案 1 :(得分:0)

我通过在引发错误的相同位置添加回调来使其工作。感谢akhilesh。希望这对其他人有帮助。

function getMap( NewMap, SearchLocation = false ) {
    var i = 0;
    var map = new google.maps.Map(document.getElementById(MapID), NewMap);
    var TrialLocationAddress;

    if( SearchLocation !== false )
    {
        var infowindow = new google.maps.InfoWindow(
            {
                content: '<b>Your Location:</b> ' + SearchLocation.formatted_address,
                size: new google.maps.Size(150, 50)
            });

        var searchMarker = new google.maps.Marker({
            position: SearchLocation.geometry.location,
            map: map,
            title: SearchLocation.formatted_address,
            icon:{
                url: "http://maps.google.com/mapfiles/kml/pal2/icon13.png"
            }
        });

        google.maps.event.addListener( searchMarker, 'click', function () {
            infowindow.open(map, searchMarker);
        });
    }

    TrialLocations.forEach(function(TrialLocation){
        console.log( TrialLocation.Address );
        getTrialLocationGeoCode(TrialLocation, function( pGeo, pLocation ){
            if( pGeo !== false && typeof pGeo != 'undefined') {
                var TrialLocationMarker = new google.maps.Marker({
                    position: pGeo.geometry.location,
                    map: map,
                    title: pLocation.Name
                });
                google.maps.event.addListener(TrialLocationMarker, 'click', function (TrialLocation, i) {
                    return function () {
                        var infowindow = new google.maps.InfoWindow(
                            {
                                content: '<b>' + pLocation.Name + '</b>',
                                size: new google.maps.Size(150, 50)
                            });
                        infowindow.open(map, TrialLocationMarker);
                    }
                });
            }
        });


    });
}
    
function getTrialLocationGeoCode( pLocation, callback )
{
    console.log ("init trial geo");
    gGeoCoder = new google.maps.Geocoder();
    if ( gGeoCoder ) {
        gGeoCoder.geocode({
            'address': pLocation.Address
        }, function (results, status)
        {
            console.log("inside the function for location geo");
            if ( status === google.maps.GeocoderStatus.OK ) {
                if ( status !== google.maps.GeocoderStatus.ZERO_RESULTS ) {
                        console.log("inside trialgeo" + results[0] );
                    callback( results[0] , pLocation);
                } else {
                    console.log("error 1");
                    return false;
                }
            } else {
                console.log("error 2");
                return false;
            }
        });
    } else {
        console.log("error 3");
        return false;
    }
}