Skip to content
Advertisement

How to loop through array of latitude/longitude pairs in AJAX call

I’m very new to PHP/AJAX and need some help… I have a leaflet map and am trying to chain two AJAX calls – the first AJAX uses data from a select value (a country ISO code).

I have then used the geonames API to find the most populated cities in that particular country. I would like to use the resulting latitude/longitude of each of these 10 cities (currently stored as pairs in $latLng) as parameters to call some other APIs (e.g. open weather) and dynamically add this information to a modal when a user clicks that particular leaflet marker. At the moment I have assigned the variable $latLng to data in the second AJAX call, but this is not working as I am unable to pass an array into the cURL routine.

Below is an example of what $latLng is currently showing in the console (for AU (Australia)) – each of the pairs are appearing on the leaflet map as a marker at the specified coordinates:

(2) [-35.2834624726481, 149.128074645996]
(2) [-33.8678499639382, 151.207323074341]
(2) [-37.8139965641595, 144.963322877884]
(2) [-31.95224, 115.861397]
(2) [-34.928661, 138.598633]
(2) [-32.92953, 151.7801]
(2) [-42.87936056387943, 147.32940673828125]
(2) [-19.26639, 146.805695]
(2) [-16.92366, 145.76613]
(2) [-12.46113366159021, 130.84184646606445]

Is there a way that I can loop through these pairs so that each one could potentially be used in the second AJAX call, depending on what pair is clicked? For example, if I click the marker at location [-12.46113366159021, 130.84184646606445] then weather data for this city will appear in a modal?

In the PHP file for the second AJAX call:

$url='https://restcountries.eu/rest/v2/alpha/' . $_REQUEST['latlng']

I am receiving the error Undefined array key "latlng"

[‘latlng’] is an array of two values. latlng[0] contains latitude and latlng[1] contains longitude.

Current code is below – any help would be appreciated. Thanks!

JS:

$("select").on('change', () => {
        $.ajax({
            url: "libs/php/getInfo.php",
            type: 'POST',
            dataType: 'json',
            data: {
                code: $('#select').val()
            },
            success: function(result) {

                console.log(result);

                if (result.status.name == "ok") {

                    var cities = result['data']['cities']['geonames'];

                    var citiesArray = [];

                    for (i=0; i<cities.length; i++) {
                        if (cities[i].countrycode == result['data']['restCountries']['alpha2Code']) {
                            citiesArray.push(cities[i]);
                        }
                    }

                    citiesArray.length = 10;
                    citiesArray.forEach(city => {
                        
                        $latLng = [city.lat, city.lng];
                        $cityMarker = L.marker($latLng)
                        .addTo($layers)
                        .bindPopup('Name: ' + city.toponymName)

                        $($cityMarker).on('click', () => {
                            $.ajax({
                                url: "libs/php/getInfoLatLng.php",
                                type: 'POST',
                                dataType: 'json',
                                data: {
                                    latlng: $latLng
                                },
                                success: function(result) {
                    
                                    console.log(result);
                    
                                    if (result.status.name == "ok") {
                    
                                        $('.modal').modal('show');
                                        console.log($latLng);
                                        $('#openWeatherResult').html('weather info goes here');
                                    }
                                },
                                error: function (jqXHR, textStatus, errorThrown) {
                                    console.log(errorThrown);
                                    console.log(textStatus);
                                    console.log(jqXHR);
                                }
                            });
                        });
                        $('.close').on('click', () => {
                            $('.modal').modal('hide');
                        })
                    });

                }

            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(errorThrown);
                console.log(textStatus);
                console.log(jqXHR);
        }
    });
});

Advertisement

Answer

Taking a simple example, based loosely on your code above:

let latLng = ['latitude', 'longitude'];
$.ajax({
    method:'POST',
    url:'myUrl.php',
    data: {latlng:latLng}
}

This will send the latLng array to your PHP script using array notation. What is sent is of the form:

myUrl.php?latlng[]=latitude&latlng[]=longitude 

What PHP will see is a latlng array as an element of $_POST:

array (size=1)
  'latlng' => 
    array (size=2)
      0 => string 'latitude' (length=8)
      1 => string 'longitude' (length=9)

And to get at those values you can use

 echo $_POST['latlng'][0];  // latitude
 echo $_POST['latlng'][1];  // longitude

To go one step further, you can add these latitude/longitude pairs to an array, and POST that:

$latLng=[['latitudeA', 'longitudeA'],['latitudeB', 'longitudeB']];
$.ajax({
    method:'POST',
    url:'myUrl.php',
    data: {latlng:latLng}
}

So now you have two levels of array, so two levels are required to access the values:

echo $_POST['latlng'][0][0];  // latitudeA
echo $_POST['latlng'][1][0];  // latitudeB

This would quickly become cumbersome and difficult to read. An alternative approach would be to use an array of objects, and using JSON.stringify() to POST them.

let locationList = [];
citiesArray.forEach(city => {
    locationList.push({lat:city.lat, long:city.long});
});
$.ajax({
   url:'myUrl.php',
   method:'POST',
   data: {
      locationList:JSON.stringify(locationList)
   }
})   

In PHP you decode the JSON string into an array of objects:

<?php
    if (isset($_POST['locationList']){
        $locationList = json_decode($_POST['locationList']);
        foreach($locationList as $location){
            // do something with the data
            echo $location->lat;       
            echo $location->long;
           
       }
    } else {
         // handle a request with no data
    }

You’ll have to work out how to incorporate this into your code.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement