Openweathermap API


weather.php
<?php 
function CallAPI($method, $url, $data = false) {
$curl = curl_init();
switch ($method) {
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data){
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data){
$url = sprintf("%s?%s", $url, http_build_query($data));
}
}
    // Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
$json = CallAPI('GET','http://api.openweathermap.org/data/2.5/weather?id=1283241&appid=XXXXXXXX');//ktm
echo $json;
?>


demoweather.html

<!DOCTYPE html>
<html>
<head>
<title>Weather Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style type="text/css">
*{
font-size: 13px;
font-family: arial;
}
</style>
</head>
<body>
<center>
<h3>Kathmandu Nepal</h3>
<p id='temperature'></p>
</center>
<script type="text/javascript">
$(document).ready(function($){
var data = "";
var jqxhr = $.ajax( "weather.php" )
.done(function(res) {
var res_data =  $.parseJSON(res);
data+='Name : '+res_data.name+'<br/>';
data+='Country : '+res_data.sys.country+'<br/>';
data+='Wind Speed : '+res_data.wind.speed+'<br/>';
data+='Temperature : '+(res_data.main.temp-273.15)+'<sup> 0 </sup>C<br/>';
$('body #temperature').html(data);
console.log(res_data);
})
.fail(function() {
alert( "error" );
});
});
</script>
</body>

</html>

Source: https://openweathermap.org/

Demo:


Share on Google Plus

About Pukar

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment

0 comments:

Post a Comment