I try to create an interactive map with Livewire and Leaflet.
For demo purposes I have a user with location and type (User, Admin, Editor).
I have a list of users and a select with type.
When I change the type, I want to only show these users on the map.
The Livewire part works, the list of users updates.
But I cannot get Leaflet to update, after the list is updated, the map disappears.
This is because it would need to reinitialized (using mymap.invalidateSize()
if I’m not wrong).
I have a view with select to get only users of type X:
<select wire:model="type">
<option value="user">User</option>
<option value="admin">Admin</option>
<option value="editor">Editor</option>
</select>
Here’s my Livewire component:
<?php
namespace App\Http\Livewire;
use App\User;
use Livewire\Component;
class Map extends Component
{
public $type = 'user';
public function render()
{
return view('livewire.map', [
'users' => User::whereType($this->type)->get(),
]);
}
}
And here’s the map blade:
<script>
document.addEventListener('DOMContentLoaded', function() {
let mymap = L.map('mapid').setView([50.1719507782763, 11.54594421386719], 6);
// skipped tile layers
@foreach ($users as $user)
L.marker([{{ $user->lat }}, {{ $user->lang }}]).addTo(mymap).bindPopup("{{ $user->name }}");
@endforeach
})
</script>
What I tried but failed with
I have tried to put an extra button in the blade that just reinitializes manually:
<button onclick="redrawMap()">Redraw</button>
And the script:
<script>
function redrawMap() {
mymap.invalidateSize();
}
</script>
Also, in the render()
method, I tried to emit the function with $this->emit('redrawMap');
I’m thankful for every pointer on how to tackle this!