Home > Web Front-end > JS Tutorial > body text

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

Barbara Streisand
Release: 2024-11-24 18:50:45
Original
961 people have browsed it

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>
Copy after login

Content Div:

<div class="tab-content">
    <div>
Copy after login

Leaflet Script:

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

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);
});
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template