Create a new Livewire component that will handle the Google Maps functionality. Let's call it
MapComponent.gophp artisan make:livewire MapComponentIn the
MapComponent, add apublicproperty to hold the Google Maps data:phppublic $mapData = null;In the
rendermethod ofMapComponent, add the Google Maps JavaScript API:csharppublic function render() { return view('livewire.map-component') ->layout('layouts.app') ->with('mapApiKey', config('services.maps.api_key')); }Make sure to create a configuration value for the Google Maps API key in the
config/services.phpfile.In the view of
MapComponent, add a container element for the Google Maps component and initialize it using JavaScript:php<div wire:ignore id="map"></div> @push('scripts') <script> function initMap() { const map = new google.maps.Map(document.getElementById('map'), { center: { lat: 37.7749, lng: -122.4194 }, zoom: 8, }); window.livewire.emit('mapDataChanged', map); } </script> <script src="https://maps.googleapis.com/maps/api/js?key={{ $mapApiKey }}&callback=initMap" defer></script> @endpushThis code initializes the Google Maps component and emits a
mapDataChangedevent with themapobject as a parameter.Create a new Livewire component that will use the Google Maps data. Let's call it
LocationComponent.gophp artisan make:livewire LocationComponentIn the
LocationComponent, define a public property that will hold the Google Maps data:phppublic $mapData = null;In the
rendermethod ofLocationComponent, add theMapComponentas a child component and pass themapDataproperty to it:csharppublic function render() { return view('livewire.location-component') ->layout('layouts.app') ->with('mapComponent', function () { return Livewire::component('map-component') ->with('mapData', $this->mapData); }); }This code creates a
MapComponentinstance with themapDataproperty passed to it.In the view of
LocationComponent, add theMapComponentas a child component:php<div> <livewire:map-component /> </div>Add the
wire:ignoreattribute to the container element of theMapComponentin themap-component.blade.phpfile. This will prevent Livewire from updating the map data automatically and allow you to update it manually.python<div wire:ignore id="map"></div> @push('scripts') <script> window.livewire.on('mapDataChanged', map => { @this.set('mapData', map); }); </script> @endpushThis code listens for the
mapDataChangedevent and sets themapDataproperty of theMapComponentinstance.
That's it! With these steps, you should now be able to share Google Maps data across separate Livewire components. When the MapComponent initializes the Google Maps component