【问题标题】:Returning values from nested functions - JavaScript [duplicate]从嵌套函数返回值 - JavaScript [重复]
【发布时间】:2015-08-01 05:02:09
【问题描述】:

我在返回以下函数的 latLng 值时遇到了一些问题。

function getUserPosition() {
    var latLng;

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            function (position) {
                latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); // #1
            }, function () {
                latLng = defaultPosition(); // #2
            }
        );
    } else {
        latLng = defaultPosition(); // #3
    }

    return latLng;
}

假设 defaultPosition() 返回一组有效的坐标。

我已经标记了三个 latLng 作业,它们是我最新的“包罗万象”方法的一部分,但仍然没有运气。

我已经查看了其他相关答案,但似乎仍然无法理解我的特定问题,很抱歉重新发布。

提前致谢。

【问题讨论】:

    标签: javascript google-maps return nested-function


    【解决方案1】:

    由于位置 API 的异步特性,您不能这样做,而是需要使用基于回调的方法,一旦位置 API 返回值,就会调用回调函数。

    function getUserPosition(callback) {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
    
            function (position) {
                callback(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
            }, function () {
                callback(defaultPosition()); // #2
            });
        } else {
            callback(defaultPosition()); // #3
        }
    }
    
    getUserPosition(function(latLng){
        //do all operations that depends on latLng here in the callback function
    })
    

    【讨论】:

    • 非常感谢,阿伦。
    猜你喜欢
    • 2011-03-23
    • 2015-03-15
    • 1970-01-01
    • 2015-07-20
    • 2014-09-01
    • 1970-01-01
    • 2020-05-11
    • 2011-03-31
    相关资源
    最近更新 更多