Leaflet – How to Fit Bounds After Adding Multiple Markers

javascriptleaflet

I am using this piece of code to display map markers pulled from a MySQL database using leaflet js on an open street map, but the map bounds are obviously hard coded at the top (with setView), and I have no idea how to set the bounds to include all iterated markers from the database. Can anyone help? I'm guessing I need to keep an array of the markers and update the bounds based on that?

var map = L.map('map').setView([51.505, -0.09], 13);

        L.tileLayer( 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png', {
          maxZoom: 18,
          attribution: '<a href="http://cartodb.com/attributions">CartoDB</a> | &copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        }).addTo(map);

        $( document ).ready(function() {
          addCompanies();
        });

        function addCompanies() {
          for(var i=0; i<companies.length; i++) {
            var marker = L.marker( [companies[i]['latitude'], companies[i]['longitude']]).addTo(map);
            marker.bindPopup( "<b>" + companies[i]['company']+"</b><br>Details:" + companies[i]['details'] + "<br />Telephone: " + companies[i]['telephone']);
          }
        }

        var companies = JSON.parse( '<?php echo json_encode($companies) ?>' );

Best Answer

You could use a featuregroup, it's like a layergroup but better.

Something like this might help.

var  myFGMarker = L.FeatureGroup;
marker = L.marker(lat_lng);
myFGMarker.addLayer(marker);
myFGMarker.addTo(map);

map.fitBounds(myFGMarker.getBounds());