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

Google Place Autocomplete Bundle Laravel Package

cethyworks/google-place-autocomplete-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require cethyworks/google-place-autocomplete-bundle
    

    Add to config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 3.x):

    Cethyworks\GooglePlaceAutocompleteBundle\CethyworksGooglePlaceAutocompleteBundle::class => ['all' => true],
    
  2. Configuration: Create config/packages/cethyworks_google_place_autocomplete.yaml:

    cethyworks_google_place_autocomplete:
        google:
            api_key: 'YOUR_GOOGLE_API_KEY'
    
  3. First Use Case: Add the form type to a Symfony form:

    use Cethyworks\GooglePlaceAutocompleteBundle\Form\SimpleGooglePlaceAutocompleteType;
    
    $builder->add('address', SimpleGooglePlaceAutocompleteType::class);
    

Key Files to Review

  • config/packages/cethyworks_google_place_autocomplete.yaml (configuration)
  • src/Form/SimpleGooglePlaceAutocompleteType.php (basic usage)
  • src/Form/ComplexGooglePlaceAutocompleteType.php (advanced usage)

Implementation Patterns

Basic Form Integration

Workflow:

  1. Use SimpleGooglePlaceAutocompleteType for minimal address input:
    $builder->add('location', SimpleGooglePlaceAutocompleteType::class, [
        'label' => 'Search Location',
        'attr' => ['class' => 'form-control'],
    ]);
    
  2. The field renders a standard text input with Google Autocomplete JS loaded automatically.

Template Rendering:

  • No manual JS inclusion needed; the bundle injects the script via Twig/HTML.
  • Customize the input with standard Symfony form theme options.

Advanced Data Fetching

Workflow:

  1. Use ComplexGooglePlaceAutocompleteType to access full place details:
    $builder->add('location', ComplexGooglePlaceAutocompleteType::class, [
        'mapped' => false, // Store raw data in a separate field
        'attr' => ['data-place-details' => 'true'],
    ]);
    
  2. Access the full response in your controller:
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
        $placeData = $form->get('location')->getData(); // Full Google Place object
    }
    

Validation and Data Handling

  • Validation: The bundle validates the input is a non-empty string by default.
  • Data Storage: Use mapped => false to store raw Google Place data (e.g., geometry, address_components) in a separate field.
  • Custom Mapping: Extend the type to map specific fields (e.g., lat, lng) to your entity:
    $builder->add('address', SimpleGooglePlaceAutocompleteType::class, [
        'lat_field' => 'latitude',
        'lng_field' => 'longitude',
    ]);
    

API Key Management

  • Store the API key in config/packages/cethyworks_google_place_autocomplete.yaml (never hardcode).
  • For dynamic keys (e.g., per-environment), use %env(GOOGLE_PLACE_API_KEY)% and reference it in the config.

Gotchas and Tips

Common Pitfalls

  1. API Key Restrictions:

    • Ensure your Google API key has the Places API enabled.
    • Restrict the key to your domain to avoid abuse (Google Cloud Console > Credentials).
  2. CORS Issues:

    • If using the bundle in a SPA or cross-domain context, ensure your API key allows referrals from your frontend domain.
  3. Deprecated Symfony Features:

    • The bundle is unmaintained (last release: 2019). Test thoroughly with Symfony 3.4/4.x.
    • For Symfony 5+, consider forking or replacing with a maintained package (e.g., FOSJsRoutingBundle + custom JS).
  4. JavaScript Conflicts:

    • The bundle loads Google’s Autocomplete JS globally. If you have multiple instances, use data-autocomplete-id to isolate them:
      {{ form_widget(form.location, {'attr': {'data-autocomplete-id': 'custom-id'}}) }}
      

Debugging Tips

  • Check Network Requests: Verify the Google Places API is being called (DevTools > Network tab).
  • Log Errors: Enable Symfony’s profiler to catch validation or API errors:
    # config/packages/dev/doctrine.yaml
    doctrine:
        orm:
            entity_managers_default:
                logging: true
    
  • Fallback for Offline: Add a fallback value in the form type options:
    $builder->add('address', SimpleGooglePlaceAutocompleteType::class, [
        'fallback_value' => 'Default Address',
    ]);
    

Extension Points

  1. Custom Templates: Override the form theme to modify the autocomplete dropdown:

    {# templates/form/fields.html.twig #}
    {% block google_place_autocomplete_widget %}
        {{ parent() }}
        <div class="custom-styles">
            <!-- Your custom dropdown styling -->
        </div>
    {% endblock %}
    
  2. Extend the Type: Create a custom type to add logic (e.g., auto-fetching coordinates):

    use Cethyworks\GooglePlaceAutocompleteBundle\Form\SimpleGooglePlaceAutocompleteType;
    
    class ExtendedGooglePlaceAutocompleteType extends SimpleGooglePlaceAutocompleteType {
        public function configureOptions(OptionsResolver $resolver) {
            $resolver->setDefaults([
                'auto_fetch_coordinates' => false,
            ]);
            parent::configureOptions($resolver);
        }
    }
    
  3. Event Listeners: Subscribe to the google_place.autocomplete.result event to process raw responses:

    // src/EventListener/GooglePlaceListener.php
    public function onAutocompleteResult(GooglePlaceEvent $event) {
        $place = $event->getPlace();
        // Manipulate $place data before form submission
    }
    

    Register in services.yaml:

    services:
        App\EventListener\GooglePlaceListener:
            tags:
                - { name: kernel.event_listener, event: google_place.autocomplete.result }
    

Performance Considerations

  • Lazy Loading: The bundle loads the Google JS library on demand. For better performance, preload it in your base template:
    {# base.html.twig #}
    <script src="https://maps.googleapis.com/maps/api/js?key={{ google_api_key }}&libraries=places"></script>
    
  • Caching: Cache API responses if you’re fetching static data (e.g., for a list of locations). Use Symfony’s cache system or a service like Redis.
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware