Total Tayangan Halaman

Selasa, 20 April 2010

Prakiraan Cuaca Memanfaatkan Web Service Google


Kelas cuaca:
<?
class cuaca
{
var $response;
var $lokasi;
var $cuaca_hari_ini;
var $cuaca;
var $info_cuaca;
var $error;

function cuaca($lokasi="yogyakarta")
{
$this->_set_lokasi($lokasi);
$this->error = false;
}

function _set_lokasi($lokasi)
{
$this->lokasi = strtolower(trim($lokasi));
}

function _dapatkan_data()
{
if (empty($this->lokasi))
{
$this->error = true;
return false;
}
$xml = new SimplexmlElement(file_get_contents("http://www.google.com/ig/".
"api?weather=".urlencode($this->lokasi)."&hl=id"));
echo "<a href=\"http://www.google.com/ig/api?weather=".
urlencode($this->lokasi)."&hl=id\">Lihat</a><br/>";
if (!$xml->weather->problem_cause)
{
$this->response = $xml->weather;
$this->_parse();
}
else
{
$this->error = true;
}
}

function _parse()
{
$this->cuaca = array();
$this->info_cuaca = $this->response->forecast_information;
$this->cuaca_hari_ini = $this->response->current_conditions;
foreach($this->response->forecast_conditions as $prakiraan_esok)
$this->cuaca[] = $prakiraan_esok;
}

function _cetak()
{
if (!$this->error)
{
echo "<ul type='circle'>";
echo "<li>Prakiraan Cuaca Kota: ".ucwords($this->lokasi)."<br/>".
$this->cuaca_hari_ini->temp_c[data]." &#8451;, ".
$this->cuaca_hari_ini->humidity[data].", ".
$this->cuaca_hari_ini->wind_condition[data]."</li>";
foreach($this->cuaca as $new)
echo "<li><b>".$new->day_of_week[data]."</b><br/><small>".
$new->condition[data]."</small><br/>".$this->_suhu($new->low[data]).
" &#8451; s.d. ".$this->_suhu($new->high[data])." &#8451;</li>";
echo "</ul>";
}
else
echo "Maaf, Prakiraan Cuaca Kota: ".ucwords($this->lokasi).
" sementara ini belum tersedia";
}

function _suhu($suhu)
{
return (strtolower($this->info_cuaca->unit_system[data])=="si")?
$suhu:(($suhu - 32)/1.8);
}
}
?>

Implementasi:
<?
$prakiraan_cuaca = new cuaca();
$prakiraan_cuaca->_dapatkan_data();
if (!empty($_GET[kota])) $prakiraan_cuaca->_set_lokasi($_GET[kota]);
$prakiraan_cuaca->_cetak();
?>

Tidak ada komentar: