2016-11-21 5 views
1

저는 JavaScript의 초보자입니다. 이제 그 일이 끝났을 때, 나는 아주 이상한 실수를 경험하고 있습니다. 현재 위치에서 현재 날씨를 표시하는 응용 프로그램을 작성 중이며 이렇게하려면 날씨 데이터에 대한 API 호출을해야했습니다. 나는 here에서 날씨 데이터를 얻었고 처음에는 내 코드가 작동 중이었고 (주어진 위도와 경도에 대한) 지역 날씨를 얻는 중이었습니다. 그러나 기능을 추가하기 위해 코드를 편집하고 코드가 갑자기 작동하지 않게되었습니다. 나는 그것을 고치려고 노력했지만 난 부끄럽다. 나는 무엇이 망가 졌는지 전혀 모른다. 나는 너희들이 도울 수 있기를 바라고있다 !!

if (navigator.geolocation) { 
    navigator.geolocation.getCurrentPosition(function(position) { 
     lat = position.coords.latitude; 
     long = position.coords.longitude; 
     console.log(lat); 
     $.get('http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + long + '&appid=00d71b03a3c50910d8f4f0ea51703bb5', function(data) { 
      console.log(data); 
      if(lat == 300 || long == 300) { 
       alert("Enable your location to see how the weather is"); 
      } else { 
       $("#location").text(data.name); 
       var weather = data.weather[0].description; 
       $("#weather").text(weather); 
       temp = Math.round((data.main.temp - 273.15) * 10)/10.0; 
       $("#temperature").text(temp + "\u00B0 C"); 
       var icon = data.weather[0].icon; 
       $("#picture").attr("src", "http://openweathermap.org/img/w/" + icon + ".png"); 
      } 
     }); 
    }); 
}; 

내가 무슨 일이 일어나고 있는지 확인하기 위해 API 호출 아래에 console.log(data)를 넣어,하지만 아무것도 출력하지 않습니다 :

여기 참조를 위해 내 코드입니다. 매우 혼란스럽게 도와주세요!

+0

문제는 다른 곳이다 ..'$ .get'가 .. 여기에 데이터가 있어야 요청의 결과를 반환해야' data.data'를 호출합니다. 왜냐하면 당신은 결과를'data'라고 부르기 때문입니다. –

+0

코드가 제 코드에서 작동합니다. jquery로 document.ready 이벤트에서 로컬로 실행하고있다. 그러나 여기서는 스택 스 니펫에서 작동하지 않습니다. 어떤 환경에서 뛰고 있습니까? – ThisClark

+0

예 .. 나는 틀렸다. 잠시 jQuery로 작업 한 적이 없다. 각도가있는 IHttpService에 익숙하다. 자동으로 result.data가 반환된다. –

답변

2

나는 파이어 폭스에서이 코드를 실행하고 api.openweathermap.org

확인하는 경우 브라우저 지원 navigator.geolocation 및 허가 공유 위치에서 JSON 데이터를 얻을.


다음 코드는 navigator.geolocation.getCurrentPosition을 무시하고 그것을 불을 강제로 .bind와 내부 fn를 호출합니다. $ .get` 아무것도 반환하지 않습니다 '경우

$(document).ready(function() { 
 
    var appId = "00d71b03a3c50910d8f4f0ea51703bb5"; 
 
    if (navigator.geolocation) { 
 

 
     // TODO: remove this for production. DEMO/DEBUG usage 
 
     navigator.geolocation.getCurrentPosition = function(fn) { 
 
      fn.bind(this, { coords : { latitude : 51.507351, longitude : -0.127758 }})(); 
 
     }; 
 

 
     navigator.geolocation.getCurrentPosition(function(position) { 
 
      try { 
 
      
 
       lat = position.coords.latitude; 
 
       long = position.coords.longitude; 
 
    
 
       $.get('//api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + long + '&appid=' + appId, function(data) { 
 
        console.log("data := %o", data);   
 
    
 
        if(lat == 300 || long == 300) { 
 
         alert("Enable your location to see how the weather is"); 
 
        } else { 
 
         $("#location").text(data.name); 
 
         var weather = data.weather[0].description; 
 
         $("#weather").text(weather); 
 
         temp = Math.round((data.main.temp - 273.15) * 10)/10.0; 
 
         $("#temperature").text(temp + "\u00B0 C"); 
 
         var icon = data.weather[0].icon; 
 
         $("#picture").attr("src", "//openweathermap.org/img/w/" + icon + ".png"); 
 
        } 
 
       }); 
 
      } catch(error) { 
 
       console.log("err := %o", error); 
 
      }    
 
     }); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<label for="location">Location</label><span id="location"></span> 
 
<label for="weather">Weather</label><div id="weather"></div> 
 
<label for="temperature">Temperature (F)</label><span id="temperature"></span> 
 
<img id="picture" src="" width="200px" height="200px" />

+0

내 위치가 켜져 있고 내가 사용하는 웹 사이트가 navigator.geolocation을 지원하고 해당 코드 조각이 작동하지 않음을 확인했습니다. ((시도하고 시간을내어 주셔서 감사합니다.) – lww515

+0

업데이트 된 스 니펫이 실행되도록 해 주셔서 감사합니다. –

+0

따라서 문제의 범위는 'getCurrentPosition' (웹 도구> 더 많은 도구> 센서를 조롱 할 수있는 센서 btw ..에서 읽습니다.) 또는 무언가가 사용자의 호출을 가로 채고 있습니다 (브라우저 확장 일 수 있음). 문제) –