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

dsyph3r/google-geolocation-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    • Add the bundle and Buzz via deps file or Git submodules (as per README).
    • Register namespaces in app/autoload.php:
      $loader->registerNamespaces([
          'Buzz'      => __DIR__.'/../vendor/Buzz/lib',
          'Google'    => __DIR__.'/../vendor/bundles',
      ]);
      
    • Enable the bundle in app/AppKernel.php:
      new Google\GeolocationBundle\GoogleGeolocationBundle(),
      
  2. Configuration:

    • Add Google API key to app/config/config.yml:
      google_geolocation:
          api_key: "YOUR_API_KEY"
      
    • Publish the config (if needed):
      php app/console config:dump-reference Google\GeolocationBundle
      
  3. First Use Case:

    • Geocode an address (e.g., in a controller):
      use Google\GeolocationBundle\Service\Geocoder;
      
      class AddressController extends Controller
      {
          public function geocodeAction($address)
          {
              $geocoder = $this->get('google_geolocation.geocoder');
              $result = $geocoder->geocode($address);
              return $this->render('address/show.html.twig', ['result' => $result]);
          }
      }
      

Implementation Patterns

Core Workflows

  1. Geocoding Addresses:

    • Use the Geocoder service to convert human-readable addresses to coordinates:
      $result = $geocoder->geocode('1600 Amphitheatre Parkway, Mountain View, CA');
      
    • Handle the response (e.g., extract latitude/longitude):
      $location = $result->getLocation();
      $lat = $location->getLat();
      $lng = $location->getLng();
      
  2. Reverse Geocoding:

    • Convert coordinates to human-readable addresses:
      $result = $geocoder->reverseGeocode(37.422, -122.084);
      $formattedAddress = $result->getFormattedAddress();
      
  3. Batch Processing:

    • Loop through addresses (e.g., from a database) and geocode in bulk:
      foreach ($addresses as $address) {
          $geocode = $geocoder->geocode($address);
          $address->latitude = $geocode->getLocation()->getLat();
          $address->longitude = $geocode->getLocation()->getLng();
          $address->save();
      }
      
  4. Caching Responses:

    • Cache geocoding results to avoid API rate limits (e.g., using Symfony’s cache):
      $cache = $this->get('cache');
      $cacheKey = 'geocode_' . md5($address);
      $result = $cache->get($cacheKey);
      
      if (!$result) {
          $result = $geocoder->geocode($address);
          $cache->set($cacheKey, $result, 86400); // Cache for 1 day
      }
      

Integration Tips

  • Forms:

    • Use the bundle with Symfony forms to validate and geocode addresses on submission:
      $builder->add('address', 'text');
      $builder->add('latitude', 'hidden');
      $builder->add('longitude', 'hidden');
      
    • Add a form event listener to geocode the address:
      $form->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
          $data = $event->getData();
          $address = $data['address'];
          $geocoder = $this->get('google_geolocation.geocoder');
          $result = $geocoder->geocode($address);
          $data['latitude'] = $result->getLocation()->getLat();
          $data['longitude'] = $result->getLocation()->getLng();
          $event->setData($data);
      });
      
  • APIs:

    • Expose geocoding as a REST endpoint:
      // src/YourBundle/Controller/GeocodeController.php
      class GeocodeController extends Controller
      {
          public function geocodeAction(Request $request)
          {
              $address = $request->request->get('address');
              $result = $this->get('google_geolocation.geocoder')->geocode($address);
              return new JsonResponse($result->toArray());
          }
      }
      
  • Twig Integration:

    • Pass geocoding results to Twig templates:
      {% for result in results %}
          <p>{{ result.formatted_address }}</p>
          <p>Lat: {{ result.location.lat }}, Lng: {{ result.location.lng }}</p>
      {% endfor %}
      

Gotchas and Tips

Pitfalls

  1. API Key Management:

    • Hardcoding API keys in config.yml is insecure. Use environment variables or Symfony’s parameter bag:
      # app/config/parameters.yml
      google_api_key: "%env(GOOGLE_API_KEY)%"
      
    • Never commit parameters.yml to version control.
  2. Rate Limits:

    • Google’s Geocoding API has usage limits. Monitor your usage and implement caching to avoid hitting limits.
    • Example error handling:
      try {
          $result = $geocoder->geocode($address);
      } catch (\Google\GeolocationBundle\Exception\GeocodingException $e) {
          $this->addFlash('error', 'Geocoding failed: ' . $e->getMessage());
      }
      
  3. Deprecated Buzz:

    • The bundle relies on the deprecated Buzz library. Consider forking the bundle and updating to Guzzle for long-term maintenance.
  4. Symfony 2 vs. 3/4:

    • The bundle is designed for Symfony 2. Some features (e.g., dependency injection) may need adjustments for newer Symfony versions. Test thoroughly.
  5. Timeouts:

    • Geocoding requests can be slow. Set a timeout for the HTTP client:
      # app/config/config.yml
      google_geolocation:
          api_key: "%google_api_key%"
          timeout: 10 # seconds
      

Debugging

  1. Enable Debugging:

    • Enable Buzz’s debug mode to inspect HTTP requests:
      $client = new Buzz\Client\Curl();
      $client->setDebug(true); // Add this to the bundle's service configuration if possible.
      
  2. Logging:

    • Log geocoding requests and responses for debugging:
      $logger = $this->get('logger');
      $logger->info('Geocoding request', ['address' => $address, 'response' => $result->toArray()]);
      
  3. Common Errors:

    • OVER_QUERY_LIMIT: You’ve exceeded Google’s usage limits. Implement caching or upgrade your plan.
    • ZERO_RESULTS: The address couldn’t be geocoded. Validate input or handle gracefully:
      if ($result->getStatus() === 'ZERO_RESULTS') {
          $this->addFlash('warning', 'Address not found.');
      }
      

Extension Points

  1. Custom Response Handling:

    • Extend the Google\GeolocationBundle\Model\GeocodeResult class to add custom fields or logic:
      class ExtendedGeocodeResult extends GeocodeResult
      {
          public function getDistance()
          {
              // Custom logic to calculate distance from a reference point.
          }
      }
      
  2. Override Services:

    • Replace the default Geocoder service with a custom implementation:
      # app/config/services.yml
      services:
          your_bundle.geocoder:
              class: Your\Bundle\Service\CustomGeocoder
              arguments: ["@google_geolocation.geocoder"]
              tags:
                  - { name: google_geolocation.geocoder }
      
  3. Add New Features:

    • Fork the bundle and add support for other Google Maps APIs (e.g., Directions, Places) by extending the base service.
  4. Testing:

    • Mock the Geocoder service in tests to avoid hitting the real API:
      $mockGeocoder = $this->getMockBuilder('Google\GeolocationBundle\Service\Geocoder')
          ->disableOriginalConstructor()
          ->getMock();
      $mockGeocoder->method('geocode')
          ->willReturn($mockResult);
      $container->set('google_geolocation.geocoder', $mockGeocoder);
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky