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

Livewire Google Places Autocomplete Laravel Package

romkaltu/livewire-google-places-autocomplete

View on GitHub
Deep Wiki
Context7

Getting Started

Install the package via Composer:

composer require romkaltu/livewire-google-places-autocomplete

Publish the configuration (optional, for API key setup):

php artisan vendor:publish --provider="RomkaLTU\LivewireGooglePlacesAutocomplete\LivewireGooglePlacesAutocompleteServiceProvider"

First Use Case: Add the component to a Livewire form for address input. Start with a basic implementation in your Livewire component:

use RomkaLTU\LivewireGooglePlacesAutocomplete\LivewireGooglePlacesAutocomplete;

public function render()
{
    return view('livewire.your-component', [
        'places' => LivewireGooglePlacesAutocomplete::make('address')
            ->apiKey(config('services.google_maps.api_key'))
            ->language('en')
            ->types(['(cities)'])
            ->debounce(500)
    ]);
}

Include the component in your Blade view:

<div>
    {{ $places }}
</div>

Implementation Patterns

1. Basic Integration with Forms

Use the component as a replacement for standard text inputs in forms:

// In your Livewire component
public $address;

public function mount()
{
    $this->places = LivewireGooglePlacesAutocomplete::make('address')
        ->apiKey(config('services.google_maps.api_key'))
        ->onChange(function ($value) {
            $this->address = $value;
        });
}

2. Customizing Place Selection

Extend functionality by handling selected places:

$places = LivewireGooglePlacesAutocomplete::make('address')
    ->onSelect(function ($place) {
        // Extract structured data (e.g., lat/lng, formatted address)
        $this->latitude = $place['geometry']['location']['lat'];
        $this->longitude = $place['geometry']['location']['lng'];
        $this->formattedAddress = $place['formatted_address'];
    });

3. Dynamic API Key Management

Use environment variables or config files for security:

// config/services.php
'google_maps' => [
    'api_key' => env('GOOGLE_MAPS_API_KEY'),
],

Then reference it in your component:

->apiKey(config('services.google_maps.api_key'))

4. Combining with Validation

Integrate with Laravel validation rules:

use Illuminate\Validation\Rule;

protected $rules = [
    'address' => ['required', Rule::unique('locations')->ignore($this->locationId)],
];

public function updated($property)
{
    $this->validateOnly($property);
}

5. Multi-Field Binding

Bind multiple fields to different place properties:

$places = LivewireGooglePlacesAutocomplete::make('address')
    ->onSelect(function ($place) {
        $this->address = $place['formatted_address'];
        $this->city = $place['address_components'][0]['long_name'] ?? null;
        $this->country = $place['address_components'][1]['long_name'] ?? null;
    });

6. Conditional Rendering

Show/hide the component based on logic:

@if ($showAddressField)
    {{ $places }}
@endif

Gotchas and Tips

Pitfalls

  1. API Key Restrictions:

    • Ensure your Google Maps API key has the Places API enabled. Without it, the component will fail silently or show errors.
    • Avoid hardcoding keys in Blade templates; always use config or environment variables.
  2. Debounce Delays:

    • Default debounce (500ms) may feel slow for users. Adjust with:
      ->debounce(300) // Faster response, but more API calls
      
  3. CORS Issues:

    • If using locally, ensure your Google Maps API key allows requests from localhost. Add http://localhost to the Restrictions > Allowed referers in the Google Cloud Console.
  4. Rate Limits:

    • Google Maps API has usage limits. Monitor usage in the Google Cloud Console to avoid unexpected charges.
  5. Livewire State Persistence:

    • If the component resets unexpectedly, ensure your Livewire component’s state is properly managed. Use public properties for fields that should persist.

Debugging Tips

  • Check Network Requests: Open Chrome DevTools (F12) and inspect the XHR tab for failed API calls. Look for 403 Forbidden errors (often API key issues) or 500 errors (server-side problems).

  • Log Place Data: Debug selected places by logging them:

    ->onSelect(function ($place) {
        \Log::info('Selected place:', $place);
    })
    
  • Fallback for No API Key: Provide a user-friendly fallback (e.g., a text input) if the API key is missing:

    @if(config('services.google_maps.api_key'))
        {{ $places }}
    @else
        <input type="text" wire:model="address" placeholder="Enter address manually">
    @endif
    

Extension Points

  1. Custom Templates: Override the default Blade template by publishing and modifying:

    php artisan vendor:publish --tag=livewire-google-places-autocomplete-views
    

    Edit resources/views/vendor/livewire-google-places-autocomplete.blade.php.

  2. Add Place Markers: Extend the component to display markers on a map (e.g., using Leaflet or Google Maps JS API):

    ->onSelect(function ($place) {
        $this->emit('placeSelected', $place);
    });
    

    Then listen in JavaScript:

    Livewire.on('placeSelected', place => {
        // Initialize map and add marker
    });
    
  3. Localization: Support multiple languages dynamically:

    ->language($this->user->preferredLanguage ?? 'en')
    
  4. Autocomplete Types: Use Google’s autocomplete types for granular control:

    ->types(['geocode', 'establishment', 'address'])
    
  5. Component Events: Trigger custom events for integration with other Livewire components:

    ->onSelect(function ($place) {
        $this->emit('addressUpdated', $place['formatted_address']);
    });
    
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.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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