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

Pelias Provider Laravel Package

geocoder-php/pelias-provider

Pelias provider for PHP Geocoder. Connects to a Pelias-compatible geocoding API (self-hosted Pelias or services like Geocode Earth and OpenRouteService) to forward and reverse geocode addresses and coordinates.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package

    composer require geocoder-php/pelias-provider
    

    Ensure your Laravel project meets the PHP version requirements (PHP 8.1+).

  2. Configure the Provider The package is designed to work with a Pelias-compatible API (e.g., Geocode Earth or a self-hosted Pelias instance). No Laravel-specific config is needed—just instantiate the provider with a Psr\Http\ClientInterface (e.g., GuzzleHttp\Client):

    use Geocoder\Provider\Pelias\Pelias;
    use GuzzleHttp\Client;
    
    $client = new Client(['base_uri' => 'https://api.geocode.earth/v1/']);
    $pelias = new Pelias($client);
    
  3. First Use Case: Geocoding an Address Integrate with Laravel’s geocoder-php/geocoder facade or service:

    use Geocoder\Geocoder;
    use Geocoder\Provider\Pelias\Pelias;
    
    $geocoder = new Geocoder();
    $geocoder->registerProvider($pelias);
    
    $results = $geocoder->geocodeQuery('1600 Pennsylvania Ave, Washington, DC');
    foreach ($results as $result) {
        dd($result->getCoordinates()); // Output: [lat, lng]
    }
    
  4. Key Documentation


Implementation Patterns

Workflows

  1. Self-Hosted Pelias Integration Deploy Pelias locally (e.g., Docker) and configure the provider to point to your instance:

    $client = new Client(['base_uri' => 'http://localhost:8080/v1/']);
    $pelias = new Pelias($client);
    
  2. Filtering Results Leverage Pelias’s advanced filters (e.g., layers, boundary.country) via the geocodeQuery method:

    $results = $geocoder->geocodeQuery('Berlin', [
        'layers' => ['address', 'poi'],
        'boundary.country' => 'de'
    ]);
    
  3. Reverse Geocoding Use the reverse() method to fetch address details from coordinates:

    $result = $geocoder->reverse(52.5200, 13.4050);
    dd($result->getStreetNumber(), $result->getPostalCode());
    
  4. Locale Support Specify a locale for localized results (e.g., de for German):

    $results = $geocoder->geocodeQuery('München', ['locale' => 'de']);
    
  5. Batch Processing Process multiple queries efficiently using Laravel’s collect() or parallel helpers:

    $addresses = ['New York', 'London', 'Tokyo'];
    $results = collect($addresses)->map(fn($addr) => $geocoder->geocodeQuery($addr));
    

Laravel-Specific Tips

  • Service Provider Binding Bind the provider in AppServiceProvider for dependency injection:

    public function register()
    {
        $this->app->singleton(Pelias::class, fn($app) => new Pelias(
            new Client(['base_uri' => config('services.pelias.endpoint')])
        ));
    }
    
  • Caching Responses Cache geocoding results to reduce API calls (e.g., using Laravel’s cache()->remember):

    $results = cache()->remember("geocode_{$query}", now()->addHours(1), fn() =>
        $geocoder->geocodeQuery($query)
    );
    
  • Error Handling Wrap API calls in a try-catch to handle rate limits or failures:

    try {
        $results = $geocoder->geocodeQuery($query);
    } catch (\Geocoder\Exception\UnsupportedOperationException $e) {
        Log::error("Geocoding failed: " . $e->getMessage());
        return response()->json(['error' => 'Service unavailable'], 503);
    }
    

Gotchas and Tips

Pitfalls

  1. API Rate Limits

    • Pelias-based APIs (e.g., Geocode Earth) enforce rate limits. Monitor your usage and implement retries with exponential backoff:
      use Symfony\Component\HttpClient\RetryStrategy;
      
      $client = new Client([
          'base_uri' => 'https://api.geocode.earth/v1/',
          'http_client' => HttpClient::create([
              'retry' => RetryStrategy::create(3, 1000)
          ])
      ]);
      
  2. Null Bounds Handling

    • Older Pelias responses may return null for bounds. Use getBounds() with null checks:
      $bounds = $result->getBounds();
      if ($bounds) {
          $sw = $bounds->getSouthWest();
          $ne = $bounds->getNorthEast();
      }
      
  3. Field Extraction Quirks

    • Some fields (e.g., confidence, accuracy) may be missing in responses. Validate before use:
      $confidence = $result->getExtraProperties()['confidence'] ?? 'N/A';
      
  4. Locale Fallbacks

    • If a locale isn’t supported, Pelias defaults to English. Test edge cases:
      $results = $geocoder->geocodeQuery('Paris', ['locale' => 'fr']);
      if ($results->isEmpty()) {
          $results = $geocoder->geocodeQuery('Paris'); // Fallback to default
      }
      

Debugging

  • Enable Debugging Use the Geocoder\Provider\Pelias\Pelias class’s debug mode to log raw API responses:

    $pelias->setDebug(true); // Logs requests/responses to storage/logs/geocoder.log
    
  • Validate API Endpoints Ensure your base_uri matches the Pelias API’s expected path (e.g., /v1/). Test with:

    curl http://your-pelias-instance/v1/search?text=test
    

Extension Points

  1. Custom Result Mapping Extend the Geocoder\Provider\Pelias\Result\PeliasResult class to add custom fields:

    class CustomPeliasResult extends PeliasResult
    {
        public function getCustomField()
        {
            return $this->getExtraProperties()['custom_field'] ?? null;
        }
    }
    
  2. HTTP Client Customization Override the default GuzzleHttp\Client to add middleware (e.g., auth):

    $client = new Client([
        'base_uri' => 'https://api.geocode.earth/v1/',
        'headers' => ['Authorization' => 'Bearer YOUR_TOKEN']
    ]);
    
  3. Laravel Events Dispatch events for geocoding results (e.g., Geocoded):

    event(new Geocoded($query, $results));
    

Configuration Quirks

  • PHP 8.1+ Requirements Ensure your Laravel project uses PHP 8.1+ (drop-in support for PHP 8.2/8.3).
  • PSR-18 Compliance The package uses Psr\Http\ClientInterface. If using Guzzle <7, install guzzlehttp/psr7 and guzzlehttp/guzzle:
    composer require guzzlehttp/psr7 guzzlehttp/guzzle
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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