繁体   English   中英

使用函数内的变量设置新变量

[英]Set a new variable using variables inside a function

我正在使用地理位置创建一个Web应用程序。 到目前为止,我已将其设置和工作,因此当用户访问时,系统会提示他们允许位置服务,然后会显示警报(非永久性,仅用于测试目的)。

我用这个:

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中? 我尝试了一些方法,但它们都返回“未定义”,所以我显然做错了。

任何帮助是极大的赞赏!

谢谢。

您必须了解javascript变量的范围,请阅读以下文章: 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();

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

UPDATE

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

你能不能直接从这个功能更新地址?

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);
}

暂无
暂无

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

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