Monday, 20 November 2023

Leaflet JS widget in Filament won't execute

For a non-profit I'm creating a Filament admin panel with a widget running a Leaflet.js map.

I've set this up according to the Filemant docs

All goes well, the data gets passed to the JS. But leaflet doesn't create the map. It seems that the L.map() command can't find the DIV I'm referrencing.

i've tried hardcoding it as const map = L.map('map'), L.map(document.getElementById('map')); L.map(this.$refs.leafletMap), L.map(this.$refs.leafletMap.id), ... none does the tric

Any help is hugely appreciated :)

AdminPanelProvider.php

class AdminPanelProvider extends PanelProvider
{
    public function boot()
    {
        FilamentAsset::register([
            Css::make('leaflet-1-9-4-css', 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css'),
            Js::make('leaflet-1-9-4-js', 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js'),
            AlpineComponent::make('visitor-heatmap-js', __DIR__ . '/../../../resources/js/leaflet-heatmap.js'),         
        ]);
    }
    
   ..
}

visitor-heatmap-widget.blade

<x-filament-widgets::widget>
    <x-filament::section>
    HEATMAP
        
        
        <div
            x-ignore
            ax-load
            ax-load-src=""
            x-data="leafletVisitorsHeatmap({
                cities: @js($data)
            })"
        >
            
                <div x-ref="leafletMap" id="map" style="width: 100%; height: 100%">

                </div>
            
        </div>
    </x-filament::section>
</x-filament-widgets::widget>

leaflet-heatmap.js (stripped to the bare minimum)

export default function leafletVisitorsHeatmap({ cities }) 
{
    return {
 
        init: function () {
            console.log('start leafletVisitorsHeatmap');
            //console.log('cities:');
            //console.log(cities);
                    
            const map = L.map(this.$refs.leafletMap.id).setView([51.505, -0.09], 13);

            const tiles = 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);
            
            
        },
        
    }
}


from Leaflet JS widget in Filament won't execute

No comments:

Post a Comment