2016-06-11 258 views
-1

我使用Openweathermap API構建天氣應用程序。該應用程序已經工作,但我有溫度轉換器仍然無法正常工作的問題。使用openweathermap API進行溫度轉換

這裏是我的HTML:

<div class='valign col s6 text-style'> 
     <div id="iconTemp"> 
      <div id="icon"></div> 
      <div id="temp"></div> 
     </div> 
     <div class='divider'></div><br> 

     <div class="text-style-details"> 
      <div class="location"></div> 
      <div id="conditions"></div> 
      <div id="wind"></div> 
     </div> 
    </div> 

而且我的javascript:

<script type="text/javascript"> 
     function ToC() { 
     var strIn = parseInt(temperature); 

     if(isNaN(strIn)) { 
      alert("Not a Number"); 
     } else { 
      var f = parseFloat(strIn); 
      var c = (f - 32) * 5/9; 

      var r = Math.round(c * 100)/100; 
      parseInt(temperature) = r.toString(); 
     } 
    } 

    function ToF() { 
     var strIn = parseFloat((temperature).toFixed(1)); 

     if(isNaN(strIn)) { 
      alert("Not a Number"); 
     } else { 
      var c = parseFloat(strIn); 
      var f = (c * 9/5) + 32; 

      var r = Math.round(f * 100)/100; 
      parseFloat((temperature).toFixed(1)) = r.toString(); 
     } 
    } 

$(document).ready(function() { 

    getLocationData(); 

    function getLocationData() { 
     $.get("http://ipinfo.io", function(location) { 
     console.log(location); 

     $('.location') 
      .append(location.city + ", ") 
      .append(location.region); 

     var units = getUnits(location.country); 
     getWeatherData(location.loc, units); 

     }, "jsonp"); 

    } 

    function getWeatherData(loc, units) { 
     lat = loc.split(",")[0] 
     lon = loc.split(",")[1] 

     var appid = "&APPID=123456abcde" 

     var url = 'http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + "&units=" + units + appid; 

     console.log(url); 

     $.get(url, function(weather) { 
     var windDir = WindDirection(weather.wind.deg); 
     var temperature = weather.main.temp; 
     var unitLabel; 

     if (units === "imperial") { 
      unitLabel = "<a href='#'>F</a>/<a href='#' onclick='ToC()'>C</a>"; 
      // temperature = parseFloat((temperature).toFixed(1)); 
     } else { 
      unitLabel = "<a href='#' onclick='ToF()'>C</a>"; 
      // temperature = parseInt(temperature); 
     } 

     // temperature; 

     // temperature = parseInt(temperature); 
     // temperature = parseFloat((temperature).toFixed(1)); 



     console.log(weather); 

     $('#icon') 
      // .append("<img src='http://openweathermap.org/img/w/" + weather.weather[0].icon + ".png'>"); 
      .append("<i class='wi wi-owm-"+weather.weather[0].id+"'></i>"); 
        // <i class="wi wi-owm-200"></i> 

     $('#temp').append(temperature + "&deg; " + unitLabel); 
     $('#conditions').append(weather.weather[0].description); 
     $('#wind').append(windDir + " " + weather.wind.speed + " knots"); 

     }, "jsonp"); 

    }; 



    function WindDirection(dir) { 
     var rose = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']; 
     var eightPoint = Math.floor(dir/45); 
     return rose[eightPoint]; 
    } 

    function getUnits(country) { 
     var imperialCountries = ['US', 'ID', 'SG', 'MY', 'BS', 'BZ', 'KY', 'PW']; 

     if (imperialCountries.indexOf(country) === -1) { 
     var units = 'metric'; 
     } else { 
     units = 'imperial'; 
     } 

     console.log(country, units); 
     return units; 
    } 

    }); 
</script> 

的應用PICT:

enter image description here

我創建功能TOC(轉換F到C)和ToF(將C轉換爲F),當我點擊標籤時,我收到一條錯誤消息「Uncaught ReferenceError:ToC is not defined」。當我點擊C(celcius)和F(華氏度)時,我希望應用程序溫度值會發生變化。

任何幫助將不勝感激,謝謝。

+0

您似乎正在定義'ToC'函數_inside_ $'.get(url,function(weather){...'ajax callback)。您需要將其移出,以便在全局範圍內進行定義和提供。 – jszobody

+1

你的'ToC'和'ToF'函數只在'$ .get'處理函數的範圍內已知。你可以將它們移動到那裏 - 你甚至可以將它們移動到$(document).ready(function(){')之上。然後,你需要將溫度傳遞給函數,或者你可以添加一個自定義的數據'屬性到你的''元素並且與之一起工作(給你的錨點一個唯一的ID,這樣你就可以很容易地訪問它們) –

回答

0

雖然寫這些功能訓練總是很好,回答你的主要問題Stion的根據openweathermap API單位換算支持:

你可以通過:&units=metric你的API調用,以獲得攝氏溫度,這樣的:

api.openweathermap.org/data/2.5/weather?lat=LATITUDE&lon=LONGITUDE&units=metric&APPID=YOUR_API_KEY 

下面是官方documentation一些信息:

Units format Description: Standard, metric, and imperial units are available.

Parameters:

units metric, imperial. When you do not use units parameter, format is Standard by default.

Temperature is available in Fahrenheit, Celsius and Kelvin units.

For temperature in Celsius use units=metric For temperature in Fahrenheit use units=imperial

Examples of API calls:

standard api.openweathermap.org/data/2.5/find?q=London

metric api.openweathermap.org/data/2.5/find?q=London&units=metric

imperial api.openweathermap.org/data/2.5/find?q=London&units=imperial

0

這是一個範圍問題。

var temperature被定義無名功能 $不用彷徨 getWeatherData 另一個匿名函數 $(文件)。就緒()!
這6個級別的深度超過您可以用飛行時間或ToC的

閱讀簡單來說:您可以訪問在此範圍內或在父範圍中聲明的所有變量。

有一個關於使用JavasScript範圍很好的解釋here (stackoverflow)

解決方案:

  • 全局變量:

    1. 添加一個全局變量var temperature = 0;權下<script>
    2. 刪除varvar temperature裏面$.get(url, function());
    3. 使用onclick(),在<head>內寫<script src="[your-js-file]">
  • 改變功能的範圍:

    1. 地方$.get(url, function(){ [HERE] });範圍
    2. ToCToF函數聲明刪除onclick='ToC()',它不再起作用。(與飛行時間相同)
    3. 添加一個id <a href="#">F</a>,如:id="toggle-unit-btn"(同樣與TOF)
    4. 添加單擊事件處理程序$('#toggle-unit-btn').on('click', ToC);
      $.get(url, function(){ [HERE] });範圍內
  • 通和來自功能的返回值: [推薦]

    1. 添加一個輸入和輸出參數,以ToCToF
function ToC(temp) { // INPUT 
    var strIn = parseInt(temp); 
    // note that I changed all temperature instances 
    // to instances of the parameter temp [could have any name] 

    if(isNaN(strIn)) { 
    alert("Not a Number"); 
    } else { 
    var f = parseFloat(strIn); 
    var c = (f - 32) * 5/9; 

    var r = Math.round(c * 100)/100; 
    temp = parseInt(r.toString()); // fix this line for any solution! 
    } 
    return temp; // OUTPUT 
} 
  • 除去onclick='ToC()',它不再工作。 (與飛行時間相同)
  • 添加一個id <a href="#">F</a>,如:id="toggle-unit-btn"(同樣與TOF)
  • 添加一個單擊事件處理程序
    $('#toggle-unit-btn').on('click',function(){temperature = ToC(temperature);});
    $.get(url, function(){ [HERE] });範圍內
    (注意,這是從以前的不同因爲它需要通過和接收溫度)