【问题标题】:Set a new variable using variables inside a function使用函数内的变量设置新变量
【发布时间】:2012-09-13 14:50:20
【问题描述】:

我正在使用地理定位创建一个网络应用程序。到目前为止,我已经设置并运行了它,因此当用户访问时会提示他们允许位置服务,然后会显示一个警报(不是永久性的,仅用于测试目的。)

我正在使用这个:

navigator.geolocation.getCurrentPosition(foundLocation, noLocation, {enableHighAccuracy:true});

function foundLocation(position)
{
    var lat = position.coords.latitude;
    var long = position.coords.longitude;
    alert('We know you are here '+ lat +','+ long);
}
function noLocation()
{
    alert('Could not find location');
}

然后我在此之外有一个名为“地址”的变量,它是 API 调用的 URL:

address = "http://api.wunderground.com/api/geolookup/hourly/conditions/astronomy/alerts/forecast/q/[LOCATION].json"

我的问题是如何将latlong 从函数中取出并将它们插入到URL 中?我尝试了一些方法,但它们都返回“未定义”,所以我显然做错了。

非常感谢任何帮助!

谢谢。

【问题讨论】:

    标签: jquery api function web-applications geolocation


    【解决方案1】:

    您必须了解 javascript 变量的范围,请阅读这篇文章:What is the scope of variables in JavaScript?

    var address = '';
    
    function setLocation(position)
    {
        var lat = position.coords.latitude;
        var long = position.coords.longitude;
        address = "http://api.wunderground.com/api/geolookup/hourly/conditions/astronomy/alerts/forecast/q/" + lat + "," + long + ".json";
    }
    

    此外,还有一种更好的方法可以解决您的问题。最简单的方法是创建一个具有唯一名称的全局对象,将变量作为该对象的属性以及更改变量的方法,例如:

    var geolocation = {};
    geolocation.latitude = 0;
    geolocation.longitude = 0;
    geolocation.address = "";
    geolocation.setLocation = function(position) {
        geolocation.latitude = position.coords.latitude;
        geolocation.longitude = position.coords.longitude;
        geolocation.address = "http://api.wunderground.com/api/geolookup/hourly/conditions/astronomy/alerts/forecast/q/" + geolocation.latitude + "," + geolocation.longitude + ".json";
    };
    geolocation.show = function() {
      alert(geolocation.latitude + " " geolocation.longitude + " " + geolocation.address);
    };
    

    等等。现在,如果您使用,文件中的任何地方:

    geolocation.setLocation(position);
    geolocation.show();
    

    它将显示来自全局对象的新值。

    更新

    请记住,javascript 中的变量或对象将是全局的,如果它周围没有包装器,就像另一个函数或对象一样。

    【讨论】:

    • 这很好,感谢您的所有帮助和解释。我还在学习,所以我很感激像你这样愿意提供帮助的人。
    • 谢谢!如果它对您有帮助,请不要忘记在“javascript 变量范围”帖子上投票给这个人!祝你好运!
    【解决方案2】:

    你不能像这样直接从函数中更新地址吗?

    navigator.geolocation.getCurrentPosition(foundLocation, noLocation, {enableHighAccuracy:true});
    var address = "http://api.wunderground.com/api/geolookup/hourly/conditions/astronomy/alerts/forecast/q/[LOCATION].json"
    
    function foundLocation(position)
    {
        var lat = position.coords.latitude;
        var long = position.coords.longitude;
        alert('We know you are here '+ lat +','+ long);
        address = address.replace('[LOCATION]', lat + ',' + long);
    }
    

    【讨论】:

    • 感谢您的帮助和回复!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 2011-12-29
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多