Jason
Jason

Reputation: 431

Leaflet custom layer control

I am trying to replace the default leaflet layer control with a custom one.

I have followed another post about creating a custom layer control.

Im able to pass the layer name through and I have checked this with console.log.

However unchecking the checkbox does not remove the layer.

  var firstLayer = omnivore.kml( 'localtions.kml' )
.on( 'ready', function() {
    map.fitBounds( firstLayer.getBounds() );

    firstLayer.eachLayer( function( layer ) {

        if ( layer instanceof L.Marker ) {
            layer.setIcon( layerIcon );
        }


        layer.on( 'click', function( e ) {
            document.getElementById( "location_img" ).innerHTML = '<img src="img/large/logo.png" height="60"><br>';
            document.getElementById( "location_name" ).innerHTML = layer.feature.properties.name;
            $( "#feature_info" ).stop();
            $( "#feature_info" ).fadeIn( "fast" );

            console.log( layer.feature.properties.name );
            $( "#feature_info" ).fadeOut( 5000 );

        } );
    } );
} )
.addTo( map );

    <div id="layercontrol">
      <label><input type="checkbox" data-layer="firstLayer">First Layer</label>
      </div>

    <script>
          $('div#layercontrol input[type="checkbox"]').on('change', function() {    
        var checkbox = $(this);
        var layer = checkbox.data().layer; 

        console.log(layer);

        // toggle the layer
        $('#checkbox').change(function() {
      if ($(this).is(':checked')) {
            map.addLayer(layer);
        } else {
            map.removeLayer(layer);
        }

    })
    });
    </script>

Upvotes: 1

Views: 3880

Answers (1)

peeebeee
peeebeee

Reputation: 2618

You look to have 2 nested change functions on the checkbox - probably not what you want. Try this....

<div id="layercontrol">
 <label><input type="checkbox" data-layer="firstLayer">First Layer</label>
</div>

<script>
      $('div#layercontrol input[type="checkbox"]').on('change', function() {    
    var checkbox = $(this);
    var layer = checkbox.data().layer; 

    console.log(layer);

    // toggle the layer

  if ($(this).is(':checked')) {
        map.addLayer(layer);
    } else {
        map.removeLayer(layer);
    }


});
</script>

Upvotes: 2

Related Questions