简体   繁体   English

全局变量返回未定义的函数外

[英]Global variable return undefined outside function

Global variables defined outside function, but still they dont alert values outside scope?在函数外部定义的全局变量,但它们仍然不警告范围外的值? as i mentioned, first alert works (value assigned) but second one not.正如我提到的,第一个警报有效(分配的值),但第二个无效。

 window.onload=getLocation();

    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);


        } else {
            x.innerHTML = "Geolocation is not supported by this browser.";
        }
    }

var lat;
var lng;

    function showPosition(position) {


      lat = position.coords.latitude.toFixed(3);
      lng = position.coords.longitude.toFixed(3);

        alert(lng); //alert done correctly

        var centerMap = new google.maps.LatLng(lat,lng);
        var directionsDisplay = new google.maps.DirectionsRenderer;
        var directionsService = new google.maps.DirectionsService;
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 14,
            center: centerMap
        });
        directionsDisplay.setMap(map);
         calculateAndDisplayRoute(directionsService, directionsDisplay);
        document.getElementById('mode').addEventListener('change', function() {
            calculateAndDisplayRoute(directionsService, directionsDisplay);
        });

    }

    alert(lng); //return nothing??

There are three problems, which I will address separately.有三个问题,我将分别解决。

- ——

First - you are assigning window.onload incorrectly.首先 - 您错误地分配了window.onload

// This calls getLocation() and assigns the returned value to window.onload
window.onload=getLocation(); 

// This is what you intended - it assigns the function getLocation to window.onload, 
// which means getLocation will be called when the window finishes loading
window.onload=getLocation; 

- ——

Second, window.onload fires after all scripts have loaded.其次, window.onload所有脚本加载触发。 So even though you define window.onload=getLocation before you call alert(lng) , the alert is going to run first because the window.onload event isn't triggered until after the script is loaded.因此,即使您在调用alert(lng)之前定义window.onload=getLocation ,警报也会首先运行,因为window.onload事件在脚本加载后才会触发。 You can test this by doing this:您可以通过执行以下操作来测试:

window.onload = function() { console.log("window load function"); };
console.log("logging after window.onload is assigned");

You will observe that the second command is executed before the first.您将观察到第二个命令在第一个命令之前执行。

If you want two things to happen one after another when the window is loaded, you can put them in the window.onload function like so:如果您希望在加载窗口时两件事情相继发生,您可以将它们放在 window.onload 函数中,如下所示:

window.onload = function () {
    getLocation();
    alert(lng);
};

Note, though, that in this particular case this still isn't enough because of item 3.但是请注意,在这种特殊情况下,由于第 3 项,这仍然不够。

- ——

Third: navigator.geolocation.getCurrentPosition() is an asynchronous function.第三: navigator.geolocation.getCurrentPosition()是一个异步函数。 Your program keeps running while it waits for a position to be gotten, and then calls the callback you've defined for it.您的程序在等待获得位置的同时继续运行,然后调用您为其定义的回调。 So even if you alert(lng) after the call to getLocation(), lng will still be NULL because getCurrentPosition hasn't triggered showPosition yet.因此,即使您在调用 getLocation( alert(lng)后发出alert(lng)lng仍将为 NULL,因为getCurrentPosition尚未触发showPosition To get all of this code to execute in the order you want, when the window has loaded, try the following:要让所有这些代码按照您想要的顺序执行,当窗口加载时,请尝试以下操作:

window.onload = function () {
    getLocation(function () {
        alert(lng);
    });
};

function getLocation(callback) {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function () {
            showPosition();
            callback();
        });
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

var lat;
var lng;

function showPosition(position) {


  lat = position.coords.latitude.toFixed(3);
  lng = position.coords.longitude.toFixed(3);

    alert(lng); //alert done correctly

    var centerMap = new google.maps.LatLng(lat,lng);
    var directionsDisplay = new google.maps.DirectionsRenderer;
    var directionsService = new google.maps.DirectionsService;
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 14,
        center: centerMap
    });
    directionsDisplay.setMap(map);
     calculateAndDisplayRoute(directionsService, directionsDisplay);
    document.getElementById('mode').addEventListener('change', function() {
        calculateAndDisplayRoute(directionsService, directionsDisplay);
    });

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM