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 Maps Bundle Laravel Package

ano/google-maps-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require ano/google-maps-bundle
    

    Register the bundle in config/bundles.php (Symfony 4.4+):

    return [
        // ...
        Ano\Bundle\GoogleMapsBundle\AnoGoogleMapsBundle::class => ['all' => true],
    ];
    
  2. Configuration: Add your Google Maps API key to config/packages/ano_google_maps.yaml:

    ano_google_maps:
        api_key: 'YOUR_GOOGLE_MAPS_API_KEY'
    
  3. First Use Case: Query geocoding in a controller:

    use Ano\Bundle\GoogleMapsBundle\Service\GeocodeAPIQuery;
    
    public function geocodeAddress(Request $request)
    {
        $query = new GeocodeAPIQuery([
            'address' => $request->input('address'),
            'sensor' => 'false',
        ]);
    
        $result = $query->getResult();
        return response()->json([
            'formatted_address' => $result->getAddress()->getFormattedAddress(),
            'coordinates' => [
                'lat' => $result->getGeometry()->getLatitude(),
                'lng' => $result->getGeometry()->getLongitude(),
            ],
        ]);
    }
    

Implementation Patterns

Core Workflows

  1. Geocoding Addresses:

    • Use GeocodeAPIQuery for address-to-coordinates conversion.
    • Chain methods for granular data extraction:
      $address = $result->getAddress();
      $coordinates = $result->getGeometry();
      
  2. Form Validation:

    • Integrate the Address constraint in Symfony forms:
      $builder->add('address', TextType::class, [
          'constraints' => [
              new Address([
                  'invalidAddressMessage' => 'Invalid address format.',
                  'notSpecificEnoughMessage' => 'Address too vague.',
              ]),
          ],
      ]);
      
  3. Service Integration:

    • Inject GeocodeAPIQuery via dependency injection:
      use Ano\Bundle\GoogleMapsBundle\Service\GeocodeAPIQuery;
      
      class MyService {
          private $geocodeQuery;
      
          public function __construct(GeocodeAPIQuery $geocodeQuery) {
              $this->geocodeQuery = $geocodeQuery;
          }
      }
      

Advanced Patterns

  • Batch Processing: Loop through addresses and cache results:

    $addresses = ['addr1', 'addr2'];
    $results = collect($addresses)->map(function ($addr) {
        return (new GeocodeAPIQuery(['address' => $addr]))->getResult();
    })->toArray();
    
  • Reverse Geocoding: Extend the bundle by implementing ReverseGeocodeAPIQuery (see "Extension Points").

  • Event-Driven: Dispatch events after geocoding (e.g., GeocodeSuccessEvent):

    $result = $query->getResult();
    $this->dispatcher->dispatch(new GeocodeSuccessEvent($result));
    

Gotchas and Tips

Pitfalls

  1. API Key Management:

    • Hardcoding keys in config is insecure. Use environment variables:
      # .env
      GOOGLE_MAPS_API_KEY=your_key_here
      
      Update config:
      ano_google_maps:
          api_key: '%env(GOOGLE_MAPS_API_KEY)%'
      
  2. Rate Limits:

    • Google Maps API enforces quotas. Monitor usage in Google Cloud Console.
    • Implement retries with exponential backoff for failed requests.
  3. Deprecation:

    • The sensor parameter is deprecated. Omit it or set to true:
      $query = new GeocodeAPIQuery(['address' => '...', 'sensor' => 'true']);
      
  4. Partial Results:

    • The bundle may return partial data if the address is ambiguous. Validate with:
      if (!$result->getAddress()->isComplete()) {
          // Handle incomplete data
      }
      

Debugging

  • Enable Debug Mode: Set debug: true in config to log API responses:

    ano_google_maps:
        api_key: '%env(GOOGLE_MAPS_API_KEY)%'
        debug: true
    
  • Error Handling: Catch GoogleMapsException for API errors:

    try {
        $result = $query->getResult();
    } catch (GoogleMapsException $e) {
        Log::error('Geocoding failed: ' . $e->getMessage());
    }
    

Extension Points

  1. Add New Services: Extend the bundle by implementing additional API wrappers (e.g., DirectionsAPIQuery):

    namespace App\Service;
    use Ano\Bundle\GoogleMapsBundle\Service\AbstractGoogleMapsQuery;
    
    class DirectionsAPIQuery extends AbstractGoogleMapsQuery {
        // Implement Directions API logic
    }
    
  2. Custom Validators: Override default validator messages or add new constraints by extending:

    namespace App\Validator\Constraints;
    use Ano\Bundle\GoogleMapsBundle\Validator\Constraints\Address;
    
    class CustomAddress extends Address {
        public function validatedBy() { return 'app.address_validator'; }
    }
    
  3. Response Transformation: Decorate the GeocodeAPIQuery service to modify responses:

    $container->set('ano_google_maps.geocode', function ($c) {
        $original = $c->get('ano_google_maps.geocode');
        return new CustomGeocodeDecorator($original);
    });
    

Performance Tips

  • Caching: Cache results for 30 minutes (Google’s recommended TTL):

    $cacheKey = 'geocode_' . md5($address);
    $result = Cache::remember($cacheKey, 1800, function () use ($query) {
        return $query->getResult();
    });
    
  • Async Processing: Use Symfony Messenger to offload geocoding to a queue:

    $message = new GeocodeMessage($address);
    $this->messageBus->dispatch($message);
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
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