2012-09-13 114 views
1

我正在使用地理位置創建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出來的功能,並將其插入到網址?我嘗試了一些方法,但都返回「未定義」,所以我顯然做錯了。

任何幫助,非常感謝!

謝謝。

回答

2

你要明白一個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(); 

它會顯示全局對象的新值。

UPDATE

請記住,在JavaScript中的變量或對象是全球性的,如果它周圍有沒有包裝,像另一個函數或對象。

+0

這很好,謝謝你的幫助和解釋。我仍然在學習,所以我很欣賞像你這樣願意幫助的人。 –

+0

謝謝!不要忘了在「javascript變量範圍」的帖子上投票,如果它可以幫助你!祝你好運! – lolol

+0

良好的通話!會做! –

1

你不能直接從這個函數更新地址嗎?

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

謝謝你的幫助和迴應! –