Home >Web Front-end >JS Tutorial >Why Does My Leaflet Map Fail to Load in a Data-Toggle Tab?

Why Does My Leaflet Map Fail to Load in a Data-Toggle Tab?

Barbara Streisand
Barbara StreisandOriginal
2024-11-24 18:50:451038browse

Why Does My Leaflet Map Fail to Load in a Data-Toggle Tab?

Leaflet Map Fails to Load in Data-toggle Tab

Issue

In a tabbed interface, a Leaflet map within a data-toggle tab fails to load correctly.

Code

Navbar:

<ul class="nav nav-tabs">
    <li class="active"><a data-toggle="tab" href="#home">Données principales</a></li>
    <li><a data-toggle="tab" href="#carte">Carte</a></li>
</ul>

Content Div:

<div class="tab-content">
    <div>

Leaflet Script:

var map = new L.Map('carteBenef');
// Configure the map here

Cause

The issue arises because Leaflet reads the map container size at initialization. When the map is placed in a hidden tab, the container size is not yet valid, resulting in incomplete tile loading.

Solution

To resolve this, you can manually trigger a map size update when the tab containing the map is displayed. This can be achieved by calling map.invalidateSize() on the tab activation event.

Example:

$('a[href="#carte"]').on('shown.bs.tab', function () {
    map.invalidateSize(true);
});

This will force Leaflet to re-evaluate the map container size and correctly load the tiles.

The above is the detailed content of Why Does My Leaflet Map Fail to Load in a Data-Toggle Tab?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn