0
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <script type="application/javascript"  src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <title> GeoNames Address</title>
  </head>
  <body>

    <label for="vol"> latidue (-90<span>&#176;</span> to 90<span>&#176;</span>)</label>
    <input type="number"  class="lat" id="lat" name="vol" min="-90" max="90">

    <label for="vol2"> longitude (0<span>&#176;</span> to 180<span>&#176;</span>)</label>
    <input type="number"  class="lat" id="lng" name="vol2" min="0" max="180">

    <button id="btnRun" > find address</button>

    <p>houseNumber: <span id="houseNumber"></span><p>
    <p>street: <span id="street"></span><p>
    <p>postalcode: <span id="postalcode"></span><p>
    <p>locality: <span id="locality"></span><p>
    <p>countryCode: <span id="countryCode"></span><p>
      <div id="error"> </div>
      <script type="text/javascript" src="libs/js/scripts.js"></script>
  </body>
</html>


$('#btnRun').click(function() {
  $.ajax(
    {
      type: 'POST',
      url: "libs/php/address.php",
      dataType: 'json',
      data: {
        lat: $('#lat').val(),
        lng: $('#lng').val()
      },
      success: function(result){
        console.log(result['data']);

        $('#houseNumber').html(result['data']['houseNumber']);
        $('#street').html(result['data']['street']);
        $('#postalcode').html(result['data']['postalcode']);
        $('#locality').html(result['data']['locality']);
        $('#countryCode').html(result['data']['countryCode']);
      },
       error: function( errorThrown){
        // error code
        console.log("we have reached error ");

        console.log(errorThrown);


       }
    });
});
<?php

  $url = 'http://api.geonames.org/addressJSON?lat=' .$_REQUEST['lat'] . '&lng=' . $_REQUEST['lng'] . '&username=sherazzi403';

  $ch = curl_init();

  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false );
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_URL, $url);

  // curl_setopt($ch, CURLOPT_POSTFIELDS)
  $result = curl_exec($ch);

  curl_close($ch);
  // api returns data as json
  // print_r($result);
  // decode the json as an associative array so that we can append it to the $output
  $decode = json_decode($result,true);

  // the 'geonames' properrty from the serialized JSON is store into the 'data'
  // element of $output
  $output['data'] = $decode['address'];
  // the correct header information for json is set and $output is converted to jsobn before send it
  header('Content-Type: application/json; charset=UTF-8');
  echo json_encode ($output);
?>


API: http://api.geonames.org/addressJSON?lat=52.358&lng=4.881&username=sherazzi403

読みやすいように、コードをきれいに保つように努めました。さらに、HTML ページは、Ajax jQuery ポスト コールを使用して PHP からの出力を読み取る Js ファイルに接続します。

ブラウザーで実行するlocalhost/address/libs/php/address.php と、パラメーターが欠落していますが、これを提供しました。なぜそれが起こるのか、そしてそれを解決する方法はわかりません。

4

0 に答える 0