0

I have the below JavaScript function to grab a country code and it's geometry as per name from a JSON object. So that when the country name is selected, the appropriate country border is added and the country code stored.

The border adds perfectly and the code is obtained within the function

However, note that I call the variable code outside of the function and when I do so it returns undefined. How can I ensure the code is recognisable outside of this function for use in others?

var code;

/* Function responsible for adding border to a given country and grabbing country code*/
function addCountryBorder(countryName) {

    $.ajax({
        url: "assets/geojson/countryBorders.geo.json",
        type: "GET",
        dataType: "json",
        data: {
            
        },
        success: function(result) {
            let features = result["features"];

            let countryFeature = findFeatureFromName(countryName);
            code = JSON.stringify(countryFeature.properties.iso_a2)
            
            console.log(code)
            return code;
            
            if (!countryFeature) {
                return;
            }
            if (border) {
                map.removeLayer(border);
            }
            border = new L.geoJSON(countryFeature["geometry"], {
                style: {
                color: "#006600",
                
                }
            }
                ).addTo(map);
            
            map.panTo(border.getBounds().getCenter());
            map.fitBounds(border.getBounds());

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


console.log(code)

0 Answers0