2016-11-25 30 views
0

我正在嘗試使用API​​構建本地天氣應用程序。 基本上我的代碼要求緯度和經度谷歌,然後把它給另一方搞清楚什麼是城市,讓它做出最終的天氣要求。API的問題

•我的緯度和經度

•我的鏈接爲女巫城市的要求是

•我有天氣對每個城市

我如何把城市裏面天氣網址做出天氣的最終請求?

對不起很麻煩,但我不太瞭解API,也不知道如何使用html處理javascript。如果你知道一個可以幫助我的來源,我會對它進行補充。 謝謝。

這裏是代碼,如果你想從項目中看到它。 http://codepen.io/Lbg232/pen/YpVgyJ?editors=1011

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script> 
<script> 

    //I don't really know what is this for. 
    var options = { 
    enableHighAccuracy: true, 
    timeout: 5000, 
    maximumAge: 0 
}; 


function success(pos) { 
    var crd = pos.coords; 

    console.log('Latitude : ' + crd.latitude); //It does print it (it works) 
    console.log('Longitude: ' + crd.longitude); 

    //This is the link ready to ask for the JSON 
    var finUrl = "http://api.wunderground.com/api/b2383764d2fa3c12/geolookup/q/" + crd.latitude + "," + crd.longitude + ".json"; 

    console.log(finUrl); //it prints the link 

}; 


function error(err) { 
    console.warn('ERROR(' + err.code + '): ' + err.message); 
}; 

navigator.geolocation.getCurrentPosition(success, error, options); 


//The request for the weather in a spacific city.  
jQuery(document).ready(function($) { 
    $.ajax({ 

    //I wanted to put the specific city and country. 
    url : "http://api.wunderground.com/api/b2383764d2fa3c12/geolookup/conditions/q/CL/Santiago.json", 

    dataType : "jsonp", 
    success : function(parsed_json) { 
    var location = parsed_json['location']['city']; 
    var temp_f = parsed_json['current_observation']['temp_c']; 
    alert("Current temperature in " + location + " is: " + temp_f); 
    }   
    }); 
}); 
</script> 

我知道是不是一個很具體的問題,這是不是對棧溢出非常apropiate但我無法找到答案。謝謝。

回答

0

你想要替換CL和聖地亞哥這個網址(http://api.wunderground.com/api/b2383764d2fa3c12/geolookup/conditions/q/CL/Santiago.json)由任何其他城市和國家?如果是的話,你可以創建一個返回城市和國家的名字一次像這樣的功能:

function getCurrentCityAndCountry(){ 
var cityAndCountry; 
var result = "http://api.wunderground.com/api/b2383764d2fa3c12/geolookup/q/" + crd.latitude + "," + crd.longitude + ".json"; 
if(result){ 
    cityAndCountry = { 
     city: location.city, 
     country:location.country_name 
    } 
} 
return cityAndCountry; 
}; 

現在,您撥打的最後一個API之前,調用上面創建拿到城市和國家名稱的功能,並把他們在URL

var cityAndCountry = getCurrentCityAndCountry(); 
url : "http://api.wunderground.com/api/b2383764d2fa3c12/geolookup/conditions/q/"+cityAndCountry.city+"/"+cityAndCountry.country+".json" 
+0

因此,網頁將發送的API,並將其存儲在「結果」就這樣? – lbg232