Home > Software engineering >  geonames weather api not fetching data
geonames weather api not fetching data

Time:11-17

Can anyone please help to find the issue why geonames API is not fetching the data?

Looks pretty straighforward, but its not working

Example http://api.geonames.org/weatherJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username=demo

html/ajax/php codes below for review

Many thanks in advance!

      <tr> 
        <td>WEATHER</td>
        <td>Returns a list of weather stations with the most recent weather observation
          <p>       
            <input type="number" id="north" placeholder="North">
            <input type="number" id="south" placeholder="South">
            <input type="number" id="east" placeholder="East">
            <input type="number" id="west" placeholder="West">
        </td>
        <td>
          <button  id="weatherBtn">SUBMIT</button>
        </td>
      </tr>

$("#weatherBtn").click(function () {
    $.ajax({
      url: "libs/php/weather.php",
      type: "POST",
      dataType: "json",
      data: {
        north: $("#north").val(),
        south: $("#south").val(),
        east: $("#east").val(),
        west: $("#west").val(),
      },
      success: function (result) {
        $("#txtA").html(result["data"][0]["stationName"]);
        $("#txtB").html(result["data"][0]["temperature"]);
        $("#txtC").html(result["data"][0]["clouds"]);
        $("#txtD").html(result["data"][0]["humidity"]);
      },
    });
  });


<?php

    
    ini_set('display_errors', 'On');
    error_reporting(E_ALL);

    $executionStartTime = microtime(true);

    $url='http://api.geonames.org/weatherJSON?formatted=true&north=' . $_REQUEST['north'] . '&south=' . $_REQUEST['south'] . '&east=' . $_REQUEST['east'] . '&west=' . $_REQUEST['west'] . '&username=karomal89&style=full';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL,$url);

    $result=curl_exec($ch);

    curl_close($ch);

    $decode = json_decode($result,true);    

    $output['status']['code'] = "200";
    $output['status']['name'] = "ok";
    $output['status']['description'] = "success";
    $output['status']['returnedIn'] = intval((microtime(true) - $executionStartTime) * 1000) . " ms";
    $output['data'] = $decode['geonames'];
    
    header('Content-Type: application/json; charset=UTF-8');

    echo json_encode($output); 

?>


CodePudding user response:

There exists no 'geonames' array key in the result of the api. But there is a key with the name 'weatherObservations'.

So try to replace the following line

$output['data'] = $decode['geonames'];

with this line:

$output['data'] = $decode['weatherObservations'];
  • Related