Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Lara Livewire Maps Laravel Package

sanderdewijs/lara-livewire-maps

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require sanderdewijs/lara-livewire-maps
    
  2. Add the @LwMapsScripts directive to your layout (once per page, after <body>):
    @LwMapsScripts
    
  3. Create a Livewire component with the map:
    php artisan make:livewire MapDemo
    
  4. Use the component in your view:
    <livewire:map-demo />
    
  5. Configure the component in your Livewire class:
    use Sanderdewijs\LaraLivewireMaps\LwMaps;
    
    public function mount() {
        $this->apiKey = env('GOOGLE_MAPS_API_KEY');
        $this->center = [52.3676, 4.9021]; // Amsterdam coordinates
        $this->zoom = 12;
    }
    
    public function render() {
        return view('livewire.map-demo', [
            'map' => LwMaps::make()
                ->apiKey($this->apiKey)
                ->center($this->center)
                ->zoom($this->zoom)
        ]);
    }
    

First Use Case: Displaying a Basic Map

  • Goal: Render a simple map with a marker.
  • Steps:
    1. Add a marker to the component:
      $this->markers = [
          ['lat' => 52.3676, 'lng' => 4.9021, 'title' => 'Amsterdam'],
      ];
      
    2. Pass markers to the LwMaps builder:
      $map = LwMaps::make()
          ->apiKey($this->apiKey)
          ->center($this->center)
          ->zoom($this->zoom)
          ->markers($this->markers);
      
    3. Render the map in your view:
      <div wire:ignore>
          {{ $map }}
      </div>
      

Implementation Patterns

Core Workflows

1. Basic Map with Markers

  • Pattern: Use the LwMaps builder to configure the map and markers.
    $map = LwMaps::make()
        ->apiKey($this->apiKey)
        ->center($this->center)
        ->zoom($this->zoom)
        ->markers($this->markers)
        ->height('500px');
    
  • View Integration:
    <div wire:ignore>
        {{ $map }}
    </div>
    

2. Handling Marker Events

  • Pattern: Use Livewire events to react to marker interactions.
    public function updatedMarkerEvent($event) {
        if ($event === 'marker-click') {
            $this->dispatch('markerClicked', data: $event['marker']);
        }
    }
    
  • View Integration:
    @this.on('markerClicked', (object) $marker => {
        alert(`Marker clicked: ${marker.title}`);
    })
    

3. Drawing Selections (Circle/Polygon)

  • Pattern: Enable drawing tools and handle selection events.
    $map = LwMaps::make()
        ->apiKey($this->apiKey)
        ->enableDrawingTools()
        ->onSelectionComplete(function ($selection) {
            $this->dispatch('selectionComplete', data: $selection);
        });
    
  • View Integration:
    @this.on('selectionComplete', (object) $selection => {
        console.log('Selection complete:', $selection);
    })
    

4. Marker Clustering

  • Pattern: Enable clustering for large datasets.
    $map = LwMaps::make()
        ->apiKey($this->apiKey)
        ->enableMarkerClustering()
        ->markers($this->markers);
    

Integration Tips

Dynamic Data Binding

  • Use Livewire properties to bind markers dynamically:
    public $markers = [];
    
    public function addMarker($lat, $lng) {
        $this->markers[] = ['lat' => $lat, 'lng' => $lng];
    }
    
  • Update the map in render():
    $map = LwMaps::make()
        ->apiKey($this->apiKey)
        ->markers($this->markers);
    

Custom Marker Icons

  • Pass custom icons via the markers array:
    $this->markers = [
        ['lat' => 52.3676, 'lng' => 4.9021, 'icon' => 'path/to/icon.png'],
    ];
    

Reactive UI Updates

  • Use Livewire's reactivity to update the map when data changes:
    public function updatedMarkers() {
        $this->map = LwMaps::make()
            ->apiKey($this->apiKey)
            ->markers($this->markers);
    }
    

Google Maps API Key Management

  • Store the API key in .env:
    GOOGLE_MAPS_API_KEY=your_api_key_here
    
  • Access it in your Livewire component:
    $this->apiKey = env('GOOGLE_MAPS_API_KEY');
    

Gotchas and Tips

Pitfalls

1. Missing @LwMapsScripts Directive

  • Issue: The map will not render if the @LwMapsScripts directive is missing or placed incorrectly.
  • Fix: Ensure the directive is included once per page, ideally right after <body> in your layout.

2. API Key Not Configured

  • Issue: The map will fail to load if no API key is provided.
  • Fix:
    • Pass the key directly to the LwMaps builder:
      LwMaps::make()->apiKey($this->apiKey)
      
    • Or configure it globally in config/lara-livewire-maps.php (if using the optional config).

3. Marker Data Format

  • Issue: Incorrect marker data format (e.g., missing lat/lng) will cause rendering errors.
  • Fix: Ensure markers follow this structure:
    $markers = [
        ['lat' => 52.3676, 'lng' => 4.9021, 'title' => 'Optional Title'],
    ];
    

4. Livewire Event Conflicts

  • Issue: Custom events (e.g., marker-click) may conflict with Livewire's internal events.
  • Fix: Use namespaced events or prefix them:
    $map->onMarkerClick(function ($marker) {
        $this->dispatch('map.marker-clicked', data: $marker);
    });
    

5. Google Maps API Restrictions

  • Issue: The Google Maps API may block requests if the API key is restricted or the domain is not whitelisted.
  • Fix:
    • Ensure your domain is added to the Google Cloud Console.
    • Use a restricted key for production to avoid abuse.

Debugging Tips

Check Console for Errors

  • Open the browser console (F12) to debug JavaScript errors, especially if the map fails to load.
  • Common errors:
    • Google Maps API error: MissingKey → API key not provided.
    • Google Maps API error: RefererNotAllowed → Domain not whitelisted.

Log Livewire Events

  • Use dd() or logger() to inspect events:
    public function updatedMarkerEvent($event) {
        \Log::info('Marker event:', $event);
    }
    

Inspect the Map Object

  • The LwMaps builder returns a renderable object. Inspect it in render():
    \Log::info('Map config:', $map->toArray());
    

Extension Points

Customizing the Map Styling

  • Pass custom map styles via the builder:
    $map = LwMaps::make()
        ->apiKey($this->apiKey)
        ->styles([
            'featureType' => 'poi',
            'elementType' => 'labels',
            'stylers' => ['visibility' => 'off'],
        ]);
    

Adding Custom Overlays

  • Use the onMapReady callback to add custom overlays:
    $map->onMapReady(function ($map) {
        new google.maps.Circle({
            map: $map,
            center: { lat: 52.3676, lng: 4.9021 },
            radius: 1000,
        });
    });
    

Extending with Additional Libraries

  • Load additional Google Maps libraries (e.g., places, drawing) via the @LwMapsScripts directive:
    @LwMapsScripts(['libraries' => ['places',
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope