全局变量的值在函数中更改后未更改

时间:2018-11-07 01:51:06

标签: javascript jquery ajax scope global

<!DOCTYPE html>
<html>
<head>
<title>Gemoetry</title>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>

<script async defer
src="https://maps.googleapis.com/maps/api/js?key=#&callback=initMap">
</script>


<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0">

<style type="text/css">
#map {
    height:500px;
    width:700px;
 }
 </style>

</head>
<body>


<div id="load-ajax"></div>
<div id="map"></div>




<script type="text/javascript">

    let latitude;
    let longitude;

    // AJAX converting address to lat and lng

    let locations = "Winston-Salem, North Carolina";

    let address = "address=" + locations;
    let url = "https://maps.googleapis.com/maps/api/geocode/json?" + address + key;

    let ajaxOutput = $('#load-ajax'); // ajax output location in HTML

    $.ajax({
        type: 'GET',
        url: url,
        data: console.log(),
        dataType: 'json',
        success: function(data) {
            console.log(data);

            let addressComponents = data.results[0].address_components;

            for (let i=0; i < addressComponents.length; i++) {
                console.log(addressComponents[i].long_name);
            }

            latitude = parseFloat(data.results[0].geometry.location.lat);
            longitude = parseFloat(data.results[0].geometry.location.lng);
        }



    });


    // Google Maps

    function initMap() {
        map = new google.maps.Map(document.getElementById('map'),
        {
            center: {lat: latitude, lng: longitude},
            zoom: 8
        });
    }
 </script>
 </body>
</html>

我正在尝试在initMap函数中使用经度和纬度变量的新值;我在全局范围内声明了它们,然后在ajax的“成功”函数中将值传递给了它们。但是变量在我的initMap函数中始终返回未定义的状态。我以为我知道全球/本地范围,但现在很困惑?为什么会这样呢?顺便说一句,以防万一,我删除了“ let key”变量。

0 个答案:

没有答案