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:

JavaScript

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:

JavaScript

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:

JavaScript

Advertisement

Answer

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

JavaScript

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

JavaScript

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

JavaScript

And to get at those values you can use

JavaScript

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

JavaScript

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

JavaScript

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.

JavaScript

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

JavaScript

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