2012-09-13 3 views
1

geolocation을 사용하여 웹 응용 프로그램을 만듭니다. 지금까지 나는 그들이 위치 서비스를 허용하라는 메시지가 사용자가 방문은, 다음 경고되게됩니다 때까지 그렇게 작업 집합이 내가이 사용하고함수 내 변수를 사용하여 새 변수 설정

(단지 테스트 목적으로, 영구적으로하지 않습니다.) :

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

내 질문은 내가 함수의 밖으로 latlong을 얻을에 삽입 할 수있는 방법이다 : 다음

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입니다이 소위 "주소"외부 변수가 URL? 몇 가지 방법을 시도했지만 모두 "정의되지 않은"값을 반환하므로 분명히 잘못된 것이 있습니다.

도움을 주시면 대단히 감사하겠습니다.

감사합니다.

답변

2

당신은 자바 스크립트 변수의 범위를 이해해야한다,이 게시물을 읽어보십시오 : 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

는 주위 래퍼는 다른 함수 또는 객체처럼 존재하지 않는 경우 자바 스크립트의 변수 또는 객체가 글로벌하다는 점을 명심하십시오.

+0

이것은 우수하며 모든 도움과 설명에 감사드립니다. 나는 아직도 배우기 때문에 도움을 기꺼이 자신과 같은 사람들에게 감사한다. –

+0

고마워요! 도움이된다면 "javascript variable scope"게시물에있는 사람을 투표하는 것을 잊지 마십시오! 행운을 빕니다! – 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

도움을 주셔서 감사합니다. –

관련 문제