3

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) ?>' );
5

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());
3

You can instantiate a LatLngBounds object and then extend() it with the coordinates of the companies. After adding the markers you can call map.fitBounds(<LatLngBounds>).

function addCompanies() {
  var bounds = L.latLngBounds() // Instantiate LatLngBounds object
  for (let c of companies) {
    let lat_lng = [c.latitude, c.longitude]
    var marker = L.marker(lat_lng).addTo(map);
    marker.bindPopup( `<b>${c.company}</b><br>Details:${c.details}<br />Telephone: ${c.telephone}`)
    bounds.extend(lat_lng)      // Extend LatLngBounds with coordinates
  }
  map.fitBounds(bounds)
}

PS.: I enhanced your code with the for...of syntax and template literals for better readability.
PPS.: Here is a jsfiddle that illustrates the logic of this solution: https://jsfiddle.net/7cavur9o/27/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.