0

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

1 Answer 1

1

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).

3
  • Thanks. One little help. When I am trying to incorporate the code its returning an error like "_ is not defined" and indicating "var markerObj = _.find( markersObj, function (obj)" this line. What I have to do to work the code perfectly? Commented Jun 15, 2013 at 13:22
  • 1
    Because you need to incorporate underscore.js in your code. Something like this should work: '<script type="text/javascript" src="cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/…>'
    – Decio
    Commented Jun 15, 2013 at 14:11
  • To be more clear: you need to include underscore.js the same way you are including leaflet.js.
    – Decio
    Commented Jun 15, 2013 at 14:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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