I had a problem with the tiles of a map not rendering on page load. I Googled for a solution but could not find a valid response, so I turned to CHatGPT. In a matter of seconds, it identified the problem and provided solutions for both my Meta Box version and a traditional web version — setTimeout.
For Meta Box
Assuming your code looks like this
<?php
$args = [
'width' => '100%',
'height' => '300px',
'zoom' => 16,
'marker' => true,
'marker_icon' => '/wp-content/uploads/sites/8/2024/07/location-dot-sharp-solid.svg',
'marker_title' => 'Click me',
'info_window' => '<p style="font-size:1rem; font-weight:500;">{mb_events_event_location_name}</p><address><small>{mb_events_event_location_street}<br>{mb_events_event_location_city} {mb_events_event_location_state:value} {mb_events_event_location_zip}</small></address>',
'js_options' => [
'mapTypeId' => 'HYBRID',
'zoomControl' => false,
],
];
rwmb_the_value( 'event_location_map', $args );
?>Add a snippet of JavaScript
<script>
document.addEventListener('DOMContentLoaded', function () {
// Wait a moment to ensure the map is fully rendered
setTimeout(function () {
// Look for Leaflet map containers if using Leaflet
const mapContainers = document.querySelectorAll('.rwmb-map-leaflet'); // Adjust if necessary
mapContainers.forEach(container => {
const mapInstance = container._leaflet_map; // MetaBox attaches the map object here
if (mapInstance && typeof mapInstance.invalidateSize === 'function') {
mapInstance.invalidateSize();
}
});
}, 300); // Slight delay helps if map was in a hidden tab
});
</script>A Code-Based Version
If you use the Leaflet CDN and create your own map, the setTimeout function is on line 31.
document.addEventListener('DOMContentLoaded', function () {
const mapDiv = document.getElementById('event-map');
if (!mapDiv) {
console.error('Map container not found.');
return;
}
// Extract coordinates from data attributes
const lat = parseFloat(mapDiv.getAttribute('data-lat'));
const lon = parseFloat(mapDiv.getAttribute('data-lon'));
if (isNaN(lat) || isNaN(lon)) {
console.error('Invalid latitude or longitude values.');
return;
}
// Initialize Leaflet map
const map = L.map('event-map').setView([lat, lon], 16);
// Add OpenStreetMap tiles (Default OSM)
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 21,
attribution: '© OpenStreetMap contributors'
}).addTo(map);
// Add Marker at provided coordinates
L.marker([lat, lon]).addTo(map)
.bindPopup('{mb_events_event_location_name}');
// Fix for partial render: Invalidate size after short delay
setTimeout(function () {
map.invalidateSize();
}, 100);
});
Leave a Reply