[GIS] leaflet fitBounds with multiple marker

javascriptjqueryleaflet

I have created two checkboxes. If I check one it will zoom to a point with marker. If I uncheck the checkbox the marker removed. Similarly second one is working. But I want to do if the two checkboxes are checked at a time it will zoom at a position where both are visible. Again when one of it checkbox is unchecked it will zoom to the points best fit position. I know that fitbounds can solve this but couldn't imliment it. Here is my code I used. Any suggestion will be a great help. Thanks

<input type="checkbox" name="One" id="one" >One</input></br>
<hr><input type="checkbox" name="Two" id="two">Two</input></br>

 $('#one').click(function(){
     if($("#one").prop('checked') === true) {
         var marker = L.marker([32.304255,-64.752098]).addTo(map).bindPopup('One');
         map.setView(new L.LatLng(32.304255,-64.752098), 16);
         marker.on('dblclick', function(){
         marker.openPopup();
         });
     }
 });
 $('#two').click(function(){
     if (this.checked) {
         var marker= L.marker([32.319343,-64.728066]).addTo(map).bindPopup('Two');
         map.setView(new L.LatLng(32.319343,-64.728066), 16);
         marker.on('dblclick', function(){
         marker.openPopup();
         });
      }
 });

var xLayer =[];
function clearLayer(){
for(var i =0; i < xLayer.length; i++)
    map.removeLayer(xLayer[i]);
    xLayer = [];
};

$('#one').click(function(){
    if($("#one").prop('checked') === false) {
    clearLayer();
    }
});
$('#two').click(function(){
    if($("#two").prop('checked') === false) {
    clearLayer();
    }
});

Best Answer

Short answer: have a look at L.LatLngBounds

Long answer: here is a working example on jsFiddle (with comments) that does what you are trying to accomplish. (It also uses underscore.js)

In general: when writing client-side JavaScript code, it is very easy to get very quickly into a mess. Try to avoid repeating code and try re-factoring common functionality into short functions. Every function, ideally, should encapsulate an atomic bit of functionality (it should not accomplish too many things).