Skip to content
Advertisement

Dynamically inserting latitude/longitude from array to weather API call in PHP

I have a leaflet map which has markers displaying the top 10 cities in a country depending on what country is chosen from a select field.

$latLng contains 10 latitude/longitude pairs and is being used to add each city at that location onto the map. Example in console (Australia):

JavaScript

The locationList array is stringified and used as data for the AJAX call which is then decoded in PHP in a foreach loop – example of first pair: {"lat":-35.283462472648096763805369846522808074951171875,"lng":149.128074645996008484871708787977695465087890625}

In the PHP file I’m trying to figure out how to dynamically add $lat and $lng to the API routine for open weather so that when a particular $cityMarker is clicked, the weather forecast for that lat/lng appears in a modal.

I’ve tried adding a foreach loop in PHP to loop through all pairs for the weather cURL routine but at the moment I am only seeing the modal display weather for the final lat/lng pair in the array – [-12.46113366159021, 130.84184646606445] in the above case. Also, the modal only appears when the marker at the above location is clicked – clicking the other city markers only shows their leaflet popup.

Is there a better way to loop over all ten pairs so that the latitude/longitude of the marker that was clicked is matched and used in the weather API call? Or an alternative method for this?

Thanks for all the help!

PHP:

JavaScript

Advertisement

Answer

Not tested, but you want to build the data portion in the loop. I changed $locationArray to $location in the ['data']['location'] portion:

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