1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

Leaflet map not re-rendering on laravel.blade template after it was hidden or the...

Discussão em 'Outras Linguagens' iniciado por Fakhri Rasyad, Outubro 18, 2024 às 00:53.

  1. I want to add a feature to hide the leaflet map after clicking on a button on top of it, however after hiding it and then click on the button to show it again, it just shows an empty section.

    The map before being hidden The map after being hidden


    The php file:
    <?php

    namespace App\Http\Livewire\DashboardChart;

    use Livewire\Component;
    use App\Models\Negara;

    class KerjasamaMap extends Component
    {
    public $negaraName;
    public $dataKerjaSamaNegara;
    public $mapVisibility;

    protected $listeners = ['setNegaraName', 'setMapVisibility'];

    public function mount()
    {
    $this->negaraName = 'Japan';
    $this->mapVisibility = true;
    $this->fetchNegaraData();
    }

    public function setNegaraName($name)
    {
    $this->negaraName = $name;
    $this->fetchNegaraData();
    }

    public function setMapVisibility($visibility = null){
    if($visibility){
    $this->mapVisibility = $visibility;
    } else {
    $this->mapVisibility = !$this->mapVisibility;
    }

    $this->emit('toggleMapVisibility');
    }

    public function fetchNegaraData()
    {
    $negaraModel = new Negara();
    $this->dataKerjaSamaNegara = $negaraModel->getNegaraWithInstansiByName($this->negaraName);
    $this->emit('dataKerjaSamaNegaraUpdate', $this->dataKerjaSamaNegara);
    }

    public function render()
    {
    return view('livewire.dashboard-chart.kerjasama-map', [
    'negaraName' => $this->negaraName,
    'dataKerjaSamaNegara' => $this->dataKerjaSamaNegara,

    ]);
    }
    }


    The blade template
    <div>
    <button wire:click="setMapVisibility">
    {{ $mapVisibility ? 'Hide Map' : 'Show Map' }}
    </button>
    <div style="display: {{ $mapVisibility ? 'block' : 'none' }};">
    <div id="map-kerjasama" style="width: 100%; height: 500px; z-index: 0;">
    </div>
    </div>
    </div>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
    let map = null;
    let markers = [];

    function initializeMap() {
    if (map !== null) {
    map.invalidateSize(); // Ensure map size is updated
    return; // Map already initialized
    map.invalidateSize(); // Ensure the map size is updated
    return;
    }

    // Initialize the map
    map = L.map('map-kerjasama', {
    scrollWheelZoom: false,
    fullscreenControl: true,
    }).setView([0.78, 113.92], 5);

    setTileLayer();
    setMapInteractionEvents();
    }

    function setTileLayer() {
    L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 19,
    attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
    }).addTo(map);
    }

    function setMapInteractionEvents() {
    const mapElement = document.getElementById('map-kerjasama');

    mapElement.addEventListener('mouseenter', () => enableMapInteraction());
    mapElement.addEventListener('mouseleave', () => disableMapInteraction());
    }

    function enableMapInteraction() {
    if (map) {
    map.scrollWheelZoom.enable();
    map.dragging.enable();
    }
    }

    function disableMapInteraction() {
    if (map) {
    map.scrollWheelZoom.disable();
    map.dragging.disable();
    }
    }

    function clearMarkers() {
    markers.forEach((marker) => {
    map.removeLayer(marker);
    });
    markers = [];
    }

    function updateMap(dataKerjaSamaNegara) {
    clearMarkers();
    dataKerjaSamaNegara.forEach((instansi) => {
    addMarker(instansi);
    });
    adjustMapBounds();
    }

    function addMarker(instansi) {
    let latitude = parseFloat(instansi.latitude);
    let longitude = parseFloat(instansi.longitude);

    if (!isNaN(latitude) && !isNaN(longitude)) {
    let marker = L.marker([latitude, longitude])
    .addTo(map)
    .bindPopup(`<b>${instansi.name}</b><br>Latitude: ${latitude}<br>Longitude: ${longitude}`);
    markers.push(marker);
    }
    }

    function adjustMapBounds() {
    if (markers.length > 0) {
    let group = new L.featureGroup(markers);
    map.fitBounds(group.getBounds());
    } else {
    alert("Masih belum ada kerjasama dengan negara ini");
    alert("Masih belum ada kerjasama dengan negara ini");
    }
    }

    function invalidateMapSize() {
    if (map) {
    setTimeout(() => {
    map.invalidateSize();
    }, 100); // Slight delay to ensure the map is visible before invalidating size
    }
    }

    function setupMutationObserver() {
    const mapElement = document.getElementById('map-kerjasama');
    const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
    if (mutation.attributeName === 'style' &&
    mapElement.style.display === 'block') {
    invalidateMapSize();
    }
    });
    });

    observer.observe(mapElement, {
    attributes: true
    });
    }

    function setupLivewireListeners() {
    Livewire.on('dataKerjaSamaNegaraUpdate', (dataKerjaSamaNegara) => {
    updateMap(dataKerjaSamaNegara);
    });
    }

    function init() {
    setupMutationObserver();
    setupLivewireListeners();
    initializeMap();
    updateMap(@json($dataKerjaSamaNegara));
    }

    init();
    // Initialize the map and update with data
    initializeMap();
    updateMap(@json($dataKerjaSamaNegara));

    // Listen for the map visibility change
    Livewire.on('mapVisibilityChanged', function(isVisible) {
    const mapElement = document.getElementById('map-kerjasama');
    mapElement.style.display = isVisible ? 'block' : 'none'; // Toggle map visibility
    if (isVisible) {
    map.invalidateSize(); // Update map size
    }
    });
    });
    </script>


    I've tried re-initializating the map, using leaflet's invalidate functions and changing the height of the map rather than using display:block, yet it still doesn't show the map how would i fix this?

    Continue reading...

Compartilhe esta Página