Leaflet JavaScript – How to FitBounds After L.GeoJSON.AJAX Has Loaded

ajaxjavascriptleaflet

I am making a Leaflet 1.3.4 map that will show members based on category. I have a php file "cs.php" that queries a MySQL and returns an option menu of distinct categories. When a category is selected it makes the selected value available to the "showUser" function. That function should clearLayers() then then bring in the appropriate GeoJSON data displaying markers with popups. All of that works fine, my problem is trying to get "fitBounds" to to zoom to fit the markers on the map. I have tried multiple scripts. Whenever fitBounds is part of the showUser function the map does not show and not errors are in the console. I don't understand what I have done wrong or forgotten or something.

UPDATE: I updated the code with suggestion to use "geojsonLayer" by @Marc_Pfister suggested in the .on data:loaded and that fixed it. I also changed to data:progress per @Stefan_Fairphone.

Here is the working example:

            <script>
            $(document).ready(function(){$("#div1").load("cs.php");});
            var m= L.map('map', {zoomControl:false}).setView([39.1, -94.6],12);
            var mopt = {
                url: 'https://api.mapbox.com/styles/v1/mapbox/streets-v10/tiles/256/{z}/{x}/{y}?access_token=<API Key>',
                options: {attribution:'© <a href="https://www.mapbox.com/map-feedback/">Mapbox</a> © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'}
            };
            var mq=L.tileLayer(mopt.url,mopt.options);
            mq.addTo(m);

            function popUp(feature,layer) {
                layer.bindPopup(........};

            var buildingLayers = new L.FeatureGroup().addTo(m);
            var geojsonLayer;               

            function showUser(str) {
            buildingLayers.clearLayers();
            geojsonLayer = new L.GeoJSON.AJAX(["geojson.php?cs="+str],{onEachFeature:popUp})
            geojsonLayer.on('data:progress', function() {
            m.fitBounds(buildingLayers.getBounds())
            })
            .addTo(buildingLayers);};
        </script>

Here is an example of the GeoJSON that "GeoJSON.php" is outputting:

{"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[-94.905793,39.416633]},"properties":{"Member_Name":"Angels Rock Bar","Contact":"Pedro Lopez","Address":"1323 Walnut","City":"Kansas City","Phone":"(816) 896-3943","Email":"info@angelsrockbarkc.com","Website":"www.angelsrockbarkc.com"}},{"type":"Feature","geometry":{"type":"Point","coordinates":[-94.541461,39.051003]},"properties":{"Member_Name":"Bar K","Contact":"Leib Dodell","Address":"501 Berkley Parkway","City":"Kansas City","Phone":"(816) 225-6961","Email":"wag@barkdogpbar.com","Website":"www.barkdogbar.com"}},{"type":"Feature","geometry":{"type":"Point","coordinates":[-94.583506,39.098954]},"properties":{"Member_Name":"The Indie on Main","Contact":"Jamie Pitts","Address":"1228 Main St.","City":"Kansas City","Phone":"(816) 283-9900","Email":"","Website":""}}

Best Answer

FeatureGroups are supposed to listen to their contents for events, but maybe that's not working for L.GeoJSON.AJAX? Try listening directly on the GeoJSON layer:

   geojsonLayer.on('data:loaded', function() {
       m.fitBounds(buildingLayers.getBounds())
   })