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

Algolia Places Provider Laravel Package

geocoder-php/algolia-places-provider

Algolia Places provider for PHP Geocoder. Geocode and reverse geocode using Algolia’s Places API with optional authentication, locale-aware queries, and PSR-18 HTTP clients. Install via Composer and use with StatefulGeocoder for localized results.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require geocoder-php/algolia-places-provider
    

    Ensure geocoder-php/geocoder is also installed (required dependency).

  2. Basic Usage

    use Geocoder\Geocoder;
    use Geocoder\Provider\AlgoliaPlaces;
    
    $geocoder = new Geocoder();
    $geocoder->registerProvider(new AlgoliaPlaces('YOUR_ALGOLIA_APP_ID', 'YOUR_ALGOLIA_API_KEY'));
    
    // Example: Search for places
    $results = $geocoder->geocodeQuery('New York')->get();
    
  3. First Use Case

    • Reverse Geocoding: Convert coordinates to human-readable addresses.
      $results = $geocoder->reverseGeocode('40.7128,-74.0060')->get();
      

Implementation Patterns

Common Workflows

  1. Searching for Places

    $results = $geocoder->geocodeQuery('coffee shops near Paris')->get();
    foreach ($results as $result) {
        echo $result->getCoordinates()->getLatitude() . ', ' . $result->getCoordinates()->getLongitude();
    }
    
  2. Filtering Results Use Algolia’s built-in filters (e.g., aroundLatLng, aroundRadius):

    $results = $geocoder->geocodeQuery('restaurants')
        ->withProviderOptions([
            'aroundLatLng' => '48.8584,2.2945', // Paris
            'aroundRadius' => '1000', // 1km radius
        ])
        ->get();
    
  3. Autocomplete

    $results = $geocoder->geocodeQuery('San Fran')->get();
    
  4. Integration with Laravel

    • Bind the provider to Laravel’s service container in config/services.php:
      'geocoder' => [
          'providers' => [
              'algolia_places' => [
                  'app_id' => env('ALGOLIA_APP_ID'),
                  'api_key' => env('ALGOLIA_API_KEY'),
              ],
          ],
      ],
      
    • Create a facade or helper:
      // app/Providers/AppServiceProvider.php
      public function register()
      {
          $this->app->singleton(Geocoder::class, function () {
              $geocoder = new Geocoder();
              $geocoder->registerProvider(new AlgoliaPlaces(
                  config('services.geocoder.providers.algolia_places.app_id'),
                  config('services.geocoder.providers.algolia_places.api_key')
              ));
              return $geocoder;
          });
      }
      
  5. Batch Processing Use Laravel’s queues to handle geocoding tasks asynchronously:

    // Dispatch a job
    GeocodeJob::dispatch('New York');
    
    // Job class
    public function handle()
    {
        $results = app(Geocoder::class)->geocodeQuery($this->query)->get();
        // Save results to DB
    }
    

Gotchas and Tips

Pitfalls

  1. API Key Restrictions

    • Algolia’s API keys may have IP restrictions or rate limits. Ensure your server’s IP is whitelisted if needed.
    • Use restricted API keys (not admin keys) for production to limit exposure.
  2. Query Limits

    • Algolia’s free tier has query limits (~100,000 queries/month). Monitor usage via Algolia Dashboard.
    • Cache frequent queries in Laravel’s cache or Redis:
      $cacheKey = 'geocode_' . md5($query);
      $results = Cache::remember($cacheKey, now()->addHours(1), function () use ($geocoder, $query) {
          return $geocoder->geocodeQuery($query)->get();
      });
      
  3. Provider Options Overrides

    • Be cautious when overriding provider options. Incorrect values (e.g., invalid aroundLatLng) may return empty results or errors.
    • Validate options before passing them:
      $options = [
          'aroundLatLng' => '40.7128,-74.0060',
          'aroundRadius' => '5000', // 5km
      ];
      if (!filter_var($options['aroundLatLng'], FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_FRACTION)) {
          throw new \InvalidArgumentException('Invalid coordinates format.');
      }
      
  4. Time Zone Handling

    • Algolia Places returns times in UTC. Convert to local time if needed:
      $result->getExtraProperties()['opening_hours'] ?? [];
      
  5. Error Handling

    • Wrap geocoding calls in try-catch blocks to handle API failures gracefully:
      try {
          $results = $geocoder->geocodeQuery($query)->get();
      } catch (\Geocoder\Exception\UnsupportedOperationException $e) {
          Log::error('Geocoding failed: ' . $e->getMessage());
          // Fallback to another provider or return cached data
      }
      

Tips

  1. Leverage Algolia’s Features

    • Use Algolia’s typo tolerance for fuzzy matching:
      $results = $geocoder->geocodeQuery('nyoork')->get(); // Returns "New York"
      
    • Customize search behavior with hitsPerPage, attributesToRetrieve, etc.:
      $options = [
          'hitsPerPage' => 5,
          'attributesToRetrieve' => ['name', 'address', 'latitude', 'longitude'],
      ];
      
  2. Debugging

    • Enable debug mode to log raw Algolia responses:
      $provider = new AlgoliaPlaces($appId, $apiKey, [
          'debug' => true,
      ]);
      
    • Check Algolia’s debugging tools for query analysis.
  3. Performance Optimization

    • Pre-filter data: Use Algolia’s indexing rules to prioritize relevant results.
    • Debounce rapid queries: Implement a simple debounce mechanism in JavaScript for frontend searches to avoid hitting rate limits.
  4. Extending Functionality

    • Custom Attributes: Algolia Places returns rich data (e.g., rating, categories). Access them via getExtraProperties():
      $rating = $result->getExtraProperties()['rating'] ?? null;
      
    • Geofencing: Combine with Laravel’s geographical queries for location-based features:
      $nearbyPlaces = Place::near($request->lat, $request->lng, 10)->get();
      
  5. Testing

    • Mock the provider in tests to avoid hitting Algolia’s API:
      $mockProvider = $this->getMockBuilder(AlgoliaPlaces::class)
          ->disableOriginalConstructor()
          ->onlyMethods(['geocodeQuery'])
          ->getMock();
      
      $mockProvider->method('geocodeQuery')
          ->willReturn(new Collection([new AddressMock()]));
      
      $geocoder->registerProvider($mockProvider);
      
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