1

I'm facing an issue with my map-based application where I'm attempting to retrieve country information when a user clicks or selects a specific country on the map. However, despite my efforts, I'm not getting the expected results. I'm seeking guidance on troubleshooting this issue.

Here's the breakdown of my setup:

I have implemented a map interface using Leaflet that displays a world map with markers representing various countries. When a user clicks on a country marker, I want to fetch additional information about that country, such as its population and capital, from an external API and display it in a modal. Here's simplified version of my html code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=, initial-scale=1">
    <title>Document</title>
    <link rel="stylesheet" href="libs/css/leaflet.css">
    <link rel="stylesheet" href="libs/css/toastify.min.css">
    <link rel="stylesheet" href="libs/css/MarkerCluster.Default.min.css">
    <link rel="stylesheet" href="libs/css/leaflet.markercluster.css">
    <link rel="stylesheet" href="libs/css/leaflet.extra-markers.min.css">
    <link rel="stylesheet" href="libs/css/font-awesome.min.css">
    <link rel="stylesheet" href="libs/css/bootstrap.min.css">
    <link rel="stylesheet" href="libs/css/Leaflet.EasyButton.css">
    <link rel="stylesheet" href="libs/css/styles.css">
</head>
<body>
    <div id="selectContainer">
        <select id="countrySelect" class="form-select shadow-sm">
            <!-- Options will be populated dynamically using JavaScript -->
        </select>
    </div>

    <div id="map"></div>

    <!-- First Modal -->
    <div id="modal1" class="modal" data-bs-backdrop="false" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
            <div class="modal-content shadow">
                <div class="modal-header bg-success bg-gradient text-white">
                    <h5 class="modal-title">Country Info</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <table class="table table-striped">
                        <tbody id="countryInfoTableBody">
                            <!-- Table rows will be generated dynamically using 
                        </tbody>
                    </table>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-success btn-sm" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
  
<script src="libs/js/leaflet.js"></script>
     <script src="libs/js/jquery.min.js"></script>
     <script src="libs/js/toastify.min.js"></script>
     <script src="libs/js/leaflet.markercluster.js"></script>
     <script src="libs/js/leaflet.extra-markers.js"></script>
     <script src="libs/js/bootstrap.min.js"></script>
     <script src="libs/js/easy-button.min.js"></script>
   <script src="libs/js/script.js"></script>
  
   
</body>
</html>

This code focuses on the map setup, marker creation, and handling the AJAX request when a user selects a country on the map.

$(document).ready(function () {
  // Initialize the Leaflet map
  var map = L.map("map", {
    layers: [streets]
  }).setView([54.7023545, -3.2765753], 6);

  // Set up basemaps
  var streets = L.tileLayer(
    "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
      attribution: '© OpenStreetMap contributors'
    }
  ).addTo(map);

  var satellite = L.tileLayer(
    "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", {
      attribution: 'Tiles &copy; Esri &mdash; Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
    }
  );

  var basemaps = {
    "Streets": streets,
    "Satellite": satellite
  };

  // Add layer control to the map
  L.control.layers(basemaps).addTo(map);

  // Add a tile layer to the map
  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
  }).addTo(map);

  // Function to add marker for a country
  function addMarker(countryName, lat, lng) {
    var marker = L.marker([lat, lng]).addTo(map);
    marker.bindPopup(countryName).openPopup();

    // Add click event listener to marker
    marker.on('click', function () {
      // Trigger AJAX call to update modal with country info
      $.ajax({
        url: "libs/php/countryinfo.php",
        type: 'POST',
        dataType: 'json',
        data: {
          country: countryName,
          lang: 'en' // Provide a default language or choose one as needed
        },
        success: function (result) {
          if (result.status.name === "ok") {
            $('#txtContinent').html(result.data[0].continent);
            $('#txtCapital').html(result.data[0].capital);
            $('#txtLanguages').html(result.data[0].languages);
            $('#txtPopulation').html(result.data[0].population);
            $('#txtArea').html(result.data[0].areaInSqKm);

            // Show the modal when the country marker is clicked
            $("#modal1").modal("show");
          }
        },
        error: function (jqXHR, textStatus, errorThrown) {
          // Handle error here
        }
      });
    });
  }

  // Handle country selection change
  $("#countrySelect").change(function () {
    var selectedCountry = $(this).val();

    // Make an API request to get country data
    $.get(`https://restcountries.com/v3.1/name/${selectedCountry}`, function (data) {
      var countryData = data[0];
      var latlng = countryData.latlng;
      var countryName = countryData.name.common;

      // Clear previous markers
      map.eachLayer(function (layer) {
        if (layer instanceof L.Marker) {
          map.removeLayer(layer);
        }
      });

      // Add a marker for the selected country
      addMarker(countryName, latlng[0], latlng[1]);
    });
  });
});

here is my api json in php that i was trying to link it to the js ajax call to handle it when user selects a country info.

<?php

    

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

    $executionStartTime = microtime(true);

    $url='http://api.geonames.org/countryInfoJSON?formatted=true&lang=' . $_REQUEST['lang'] . '&country=' . $_REQUEST['country'] . '&username=mohi';

    $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); 

?>

thank you i look foward to your feedback

Israphel
  • 11
  • 1
  • It's a good idea to describe _where it (seems it) fails_ and _what you expect_. If you receive an error message _post it here_. What I notice is that in your PHP script you modify an `$output` variable that does not exist. – David Aug 30 '23 at 08:06
  • hi david its not showing any errors in the devtool but its still empty when you select a country in the map and then click on the fist modal which is called country info . it doestnt filter out the data . like the country name and so on. – Israphel Aug 30 '23 at 08:14
  • What value does `countryName` contain within the marker `click` function? Does it contain what you think it will contain? – Professor Abronsius Aug 30 '23 at 09:17
  • @Israphel As I said before, inside your PHP you modify an `$output` variable that does not exist which will ultimately result in a PHP error. Do a `console.log(result)` inside your `success` AJAX function (but _before_ the `if (...)`) and see what the server sends back to you. – David Aug 30 '23 at 11:06

1 Answers1

0

It seems the curl and PHP code works as you expected. I am wondering if there is any issue with ajax call and get country name from Map. I recommend 2 cases.

  • Check countryName when Ajax call
  • Check response via console.log or browser network response.

Then you will see more useful solutions.

Hiro Doublin
  • 1
  • 2
  • 13