2016-11-25 63 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