Java脚本当前地理位置

java script current geolocation

本文关键字:地理位置 脚本 Java      更新时间:2023-09-26

我需要在我的web应用程序中找到我自己。我使用谷歌地图来固定我的位置。我的问题是函数返回我的当前位置:

function setLocation() {
            var temp = { lat: 0, lng: 0 };
            navigator.geolocation.getCurrentPosition(function (position, temp) {
                //here is all ok, temp.lat and tem.lng are assigned correctly
                temp.lat = position.coords.latitude;
                temp.lng = position.coords.longitude;
            });
            //here temp.lat and temp.lng are again 0    
            return temp;
        }

我在代码中添加了一些注释来描述问题。我做错了什么?谢谢你的阅读。注:我是java脚本新手。

问题是你正在使用异步函数

返回值不正确,因为getCurrentPosition()尚未执行。您必须使用回调函数,该函数将在getCurrentPosition()完成后传递结果。正如Mike C所说,异步函数的更详细描述可以在如何从异步调用返回响应中找到?

function setLocation(callback)
{
    var temp = {
        lat: 0,
        lng: 0
    };
    navigator.geolocation.getCurrentPosition(function (position, temp)
    {
        temp.lat = position.coords.latitude;
        temp.lng = position.coords.longitude;
        if ("function" === typeof callback)
        {
            callback(temp);
        }
    });
    return;
}

setLocation(function (coords)
{
    // This will alert the correct data
    alert(coords.lat + " " + coords.lng);
});

承诺是一个更好的解决方案

回调会很快失控,所以我建议使用Promise对象。教程在https://davidwalsh.name/promises。其主要思想是,在使用异步任务时,您可以拥有易于阅读/理解的代码流。您的代码的一个例子是。

function setLocation()
{
    return new Promise(function (resolve)
    {
        var temp = {
            lat: 0,
            lng: 0
        };
        navigator.geolocation.getCurrentPosition(function (position, temp)
        {
            temp.lat = position.coords.latitude;
            temp.lng = position.coords.longitude;
            resolve(temp);
        });
        return;
    });
}
setLocation
    .then(function (coords)
    {
        // This will alert the correct data
        alert(coords.lat + " " + coords.lng);
    });