[GIS] Creating drop down list to zoom into selected country for Leaflet maps

htmlleaflet

Using leaflet control, how do I create a drop down menu which lists country names?

When selecting a country on this list, the map will zoom into the selected country on that map.

countriesLayer = L.geoJson(countries,
            {
                onEachFeature: countriesOnEachFeature
            }
        ).addTo(map);

This layer loads my countries onto the map from my geojson file.

var geoJsonFeatures = [];
function countriesOnEachFeature(feature, layer){
        if (feature.properties && feature.properties.Country){
            geoJsonFeatures.push(feature);
        }
}

And then I have a loaded array which holds my geojson data as objects in the array.

 var legend = L.control({position: 'bottomright'});  
 legend.onAdd = function (map) {  
    var div = L.DomUtil.create('div', 'info legend');  
    var dropDownContent ='<select>';  
    for (var i = 0; i < uniqueCountryArray.length; i++ ){  
        dropDownContent += '<option value=' + "'" + uniqueCountryArray[i]["ISO3"] + "'>" + uniqueCountryArray[i]["Country"] + '</option>';  
       }  
        dropDownContent += '</select>';  
        div.innerHTML = dropDownContent;  
        div.firstChild.onmousedown = div.firstChild.ondblclick = L.DomEvent.stopPropagation;  
        return div;  
};

Next, I created the drop down list with it's ISO 3 code value attached to it.

$('select').change(function(){ //when user selects a country from the drop down list
            var selectedCountry = document.getElementById('ddVal').value;
            for (i=0 ; i < geoJsonFeatures.length; i++){//zooms to selected country on match
                if(selectedCountry == geoJsonFeatures[i].properties.ISO_3_CODE){
                    map.fitBounds(geoJsonFeatures[i].getBounds());
                }
            }
});

I get the ISO 3 code value from the select, compare it to the geoJson ISO 3 code in the array. When it matches, I want to use the object in the geoJson array to center it to the country selected on my Leaflet map.

I am certain that I am using the getBounds() function wrongly.

Best Answer

Leaflet uses an internal ID, set it to county name or ISO 3 code, this must be a unique value. You do this in the forEachFeature function.

function forEachFeature(feature, layer) {
            // Tagging each state poly with their name for the search control.
            layer._leaflet_id = feature.properties.STATE_NAME;

On your dropdown Get the ID or Value that corresponds to the Leafet unique ID and pass it to a function, in my case it was called polySelect.

polySelect(ui.item.label);

That function fires off a click event, and zooms to it.

// fire off click event and zoom to polygon  
    function polySelect(a){
        map._layers[a].fire('click');  // 'clicks' on state name from search
        var layer = map._layers[a];
        map.fitBounds(layer.getBounds());  // zooms to selected poly