Using existing lat/lng leaflet markers in separate AJAX function / API call

I have a leaflet map with markers showing the top cities in a chosen country. When a marker is clicked, the lat/lng of that city is used in an AJAX call and a modal displaying weather information for the city pops up through use of a PHP cURL routine to a weather API. A couple of easyButtons appear after this click event fires.

I would now like to add another modal containing different info for the same city that will pop up when the user clicks one of these easyButtons, by using another API that utilises the same lat/lng values as used in the weather call.

I am cautious that my main function is now getting very long and complex. Additionally, I’m aware that the $cityMarker click function wouldn’t work for this new modal/easy Button as it requires a new click. Therefore I think it would be best to create a separate function.

Is there a simple way to be able to access the lat/lng values in the AJAX call for use outside the function scope – i.e. when the user clicks the new easyButton the lat/lng data from the current marker can be used? Or any other suggestions as to how I can achieve this functionality?

Any help is much appreciated – thank you!

JS:

var locationList = [];
                    citiesArray.forEach(city => {
                        locationList.push({
                            lat: city.lat,
                            lng: city.lng,
                            cityName: city.toponymName
                        });
                    });
                    
                    console.log(locationList)
                    for (var i=0; i < locationList.length; i++) {
                        $cityMarker = L.marker(new L.latLng([locationList[i]['lat'], locationList[i]['lng']]))
                        .addTo($layers)
                        .bindPopup(locationList[i]['cityName'])
                    
                
                        $($cityMarker).on('click', (event) => {
                            var marker = event.target;
                            $.ajax({
                                url: "getLatLngInfo.php",
                                type: 'POST',
                                data: {
                                    lat: marker.getLatLng().lat,
                                    lng: marker.getLatLng().lng
                                },
                                success: function(result) {
                    
                                    console.log(result);
                                    $weatherButton.enable();
                                    $wikiButton.enable();
                                        $('#weather').modal('show');

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

$($wikiButton).on('click'.............

PHP:

<?php

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

    $executionStartTime = microtime(true) / 1000;
    
    $lat = $_POST['lat'];
    $lng = $_POST['lng'];

    // openWeather

    $openWeatherUrl='api.openweathermap.org/data/2.5/weather?lat=' . $lat . '&lon='  . $lng  . '&lang=en&units=metric&appid=demo';
    
    $openWeatherch = curl_init();
    curl_setopt($openWeatherch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($openWeatherch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($openWeatherch, CURLOPT_URL,$openWeatherUrl);
    
    $openWeatherResult = curl_exec($openWeatherch);
    
    curl_close($openWeatherch);
    
    $openWeather = json_decode($openWeatherResult, true);

    // geoNames wikipedia

    $geoNamesWikiUrl='http://api.geonames.org/findNearbyWikipediaJSON?lat=' . $lat . '&lng=' . $lng . '&username=demo';
    
    $geoNamesWikich = curl_init();
    curl_setopt($geoNamesWikich, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($geoNamesWikich, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($geoNamesWikich, CURLOPT_URL,$geoNamesWikiUrl);
    
    $geoNamesWikiResult = curl_exec($geoNamesWikich);
    
    curl_close($geoNamesWikich);
    
    $geoNamesWiki = json_decode($geoNamesWikiResult, true);
    
    $output['status']['code'] = "200";
    $output['status']['name'] = "ok";
    $output['status']['description'] = "mission saved";
    $output['status']['returnedIn'] = (microtime(true) - $executionStartTime) / 1000 . " ms";
    $output['data']['openWeather'] = $openWeather;
    $output['data']['geoNamesWiki'] = $geoNamesWiki;
    
    header('Content-Type: application/json; charset=UTF-8');
    
    echo json_encode($output);

?>

Answer

You can store the clicked Marker in a variable clickedMarker:

var locationList = [];
var clickedMarker;
                    citiesArray.forEach(city => {
                        locationList.push({
                            lat: city.lat,
                            lng: city.lng,
                            cityName: city.toponymName
                        });
                    });
                    
                    console.log(locationList)
                    for (var i=0; i < locationList.length; i++) {
                        $cityMarker = L.marker(new L.latLng([locationList[i]['lat'], locationList[i]['lng']]))
                        .addTo($layers)
                        .bindPopup(locationList[i]['cityName'])
                    
                
                        $($cityMarker).on('click', (event) => {
                            var marker = event.target;
                            clickedMarker = marker;
                            $.ajax({
                                url: "getLatLngInfo.php",
                                type: 'POST',
                                data: {
                                    lat: marker.getLatLng().lat,
                                    lng: marker.getLatLng().lng
                                },
                                success: function(result) {
                    
                                    console.log(result);
                                    $weatherButton.enable();
                                    $wikiButton.enable();
                                    $('#weather').modal('show');

                                },
                                error: function (jqXHR, textStatus, errorThrown) {
                                    console.log(errorThrown);
                                    console.log(textStatus);
                                    console.log(jqXHR);
                                
                                }
                            });
                        });
                    }
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(errorThrown);
                console.log(textStatus);
                console.log(jqXHR);
        }
    });
});
$($wikiButton).on('click',()=>{
    var marker = clickedMarker;

    $.ajax({
                                url: "getLatLngInfo.php",
                                type: 'POST',
                                data: {
                                    lat: marker.getLatLng().lat,
                                    lng: marker.getLatLng().lng
                                },
                                success: function(result) {

                                    console.log(result);
                                    $weatherButton.enable();
                                    $wikiButton.enable();
                                    $('#weather').modal('show');

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

                                }
                            });
});

Leave a Reply

Your email address will not be published. Required fields are marked *