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

Open Cage Provider Laravel Package

geocoder-php/open-cage-provider

OpenCage provider for Geocoder PHP. Adds forward and reverse geocoding via the OpenCage Geocoding API, with address lookups by text or coordinates and results normalized to Geocoder’s model for easy integration in PHP apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps for First Use

  1. Install Dependencies:
    composer require geocoder-php/open-cage-provider willdurand/geocoder
    
  2. Configure API Key: Add your OpenCage API key to .env:
    OPENCAGE_API_KEY=your_api_key_here
    
  3. Basic Geocoding: Use the Geocoder facade in a Laravel controller or service:
    use Geocoder\Geocoder;
    use Geocoder\ProviderManager;
    
    public function geocodeAddress()
    {
        $geocoder = new ProviderManager();
        $geocoder->registerProvider('opencage', new \Geocoder\Provider\OpenCage\OpenCageProvider(env('OPENCAGE_API_KEY')));
    
        $results = $geocoder->geocode('1600 Amphitheatre Parkway, Mountain View');
        $coordinates = $results->first()->getCoordinates();
    
        return response()->json(['coordinates' => $coordinates]);
    }
    
  4. Reverse Geocoding: Convert coordinates to an address:
    $results = $geocoder->reverse($coordinates);
    $address = $results->first()->getFormattedAddress();
    

Where to Look First

First Use Case: Address Validation

Validate user input during form submission (e.g., signup or checkout):

public function validateAddress(Request $request)
{
    $geocoder = app(ProviderManager::class);
    $results = $geocoder->geocode($request->address);

    if ($results->count() === 0) {
        return back()->withErrors(['address' => 'Invalid address']);
    }

    return back()->with('success', 'Address validated');
}

Implementation Patterns

Core Workflows

  1. Geocoding Workflow:

    • Input: User-provided address string (e.g., "123 Main St, Boston").
    • Process: Call geocode() with the address.
    • Output: Collection of Result objects with coordinates, formatted addresses, and confidence scores.
    • Example:
      $results = $geocoder->geocode('123 Main St, Boston', [
          'parameters' => ['bounded' => 1, 'language' => 'en']
      ]);
      
  2. Reverse Geocoding Workflow:

    • Input: Latitude/longitude (e.g., [42.3601, -71.0589]).
    • Process: Call reverse() with coordinates.
    • Output: Collection of Result objects with structured address components (street, city, country, etc.).
    • Example:
      $coordinates = [42.3601, -71.0589];
      $results = $geocoder->reverse($coordinates);
      $address = $results->first()->getAddress();
      
  3. Ambiguity Handling:

    • Use the parameters array to reduce ambiguous results (e.g., duplicate street names).
    • Example:
      $results = $geocoder->geocode('Main St', [
          'parameters' => ['countrycode' => 'US', 'city' => 'Boston']
      ]);
      

Integration Tips

  1. Laravel Service Provider: Bind the provider to the container for reuse:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(ProviderManager::class, function ($app) {
            $manager = new ProviderManager();
            $manager->registerProvider('opencage', new \Geocoder\Provider\OpenCage\OpenCageProvider(env('OPENCAGE_API_KEY')));
            return $manager;
        });
    }
    

    Now inject ProviderManager anywhere:

    use Geocoder\ProviderManager;
    
    public function __construct(private ProviderManager $geocoder) {}
    
  2. Caching Responses: Cache geocoding results to reduce API calls (e.g., for static addresses like business locations):

    public function getCachedGeocode(string $address)
    {
        return Cache::remember("geocode_{$address}", now()->addHours(1), function () use ($address) {
            return $this->geocoder->geocode($address);
        });
    }
    
  3. Batch Processing: Use Laravel queues to process bulk geocoding (e.g., importing a CSV of addresses):

    // Dispatch a job
    GeocodeAddressJob::dispatch($address)->onQueue('geocoding');
    
    // Job class
    public function handle()
    {
        $results = $this->geocoder->geocode($this->address);
        // Store results in DB
    }
    
  4. Structured Address Access: Extract components from OpenCageAddress (e.g., for database storage):

    $address = $results->first()->getAddress();
    $structured = [
        'street' => $address->getStreetName(),
        'city' => $address->getLocality(),
        'country' => $address->getCountry(),
        'geohash' => $address->getGeohash(),
        'what3words' => $address->getWhat3Words(),
    ];
    
  5. Confidence Filtering: Filter results by confidence score (added in v4.7.0):

    $highConfidenceResults = $results->filter(function ($result) {
        return $result->getConfidence() >= 7; // OpenCage confidence score (0-10)
    });
    

Common Use Cases

Use Case Implementation Pattern Example
User Onboarding Validate address during signup. Check geocode() results before saving user data.
Delivery Services Geocode pickup/drop-off addresses. Use geocode() + reverse() for real-time tracking.
Local Search Find nearby locations (e.g., restaurants). Combine with Laravel Scout or a spatial database (e.g., PostGIS).
Analytics Enrich user data with geospatial metadata. Store geohash or what3words in user profiles for regional analysis.
Compliance Ensure accurate address data for shipping/tax. Validate with geocode() and log confidence scores.

Gotchas and Tips

Pitfalls

  1. API Key Management:

    • Gotcha: Hardcoding API keys in code or version control.
    • Fix: Always use Laravel’s .env and restrict access to the file.
    • Tip: Rotate keys periodically and use Laravel’s env() helper.
  2. Rate Limiting:

    • Gotcha: Hitting OpenCage’s free tier limit (2,500 requests/day).
    • Fix:
      • Implement caching (Redis/Memcached) for frequent queries.
      • Use Laravel queues to batch requests.
      • Monitor usage via OpenCage’s dashboard or a custom logger.
    • Tip: Upgrade to a paid plan if scaling beyond free limits.
  3. Ambiguous Results:

    • Gotcha: Duplicate street names (e.g., "Main St" in multiple cities).
    • Fix: Use the parameters array to narrow results:
      $results = $geocoder->geocode('Main St', [
          'parameters' => ['countrycode' => 'US', 'city' => 'Boston']
      ]);
      
    • Tip: Combine with confidence scoring to filter low-confidence matches.
  4. PHP Version Mismatch:

    • Gotcha: Using PHP < 8.0 (package drops support for PHP 7.4 in v4.4.0).
    • Fix: Update Laravel to PHP 8.0+ or pin an older Geocoder version (not recommended).
    • Tip: Check Laravel’s PHP version requirements.
  5. Caching Stale Data:

    • Gotcha: Cached geocoding results become outdated (e.g., new street names).
    • Fix: Set short TTL (e.g., 1 hour) for dynamic addresses or disable caching for critical data.
    • Tip: Use event-based invalidation (e.g., address_updated) to clear cache.
  6. Provider Registration:

    • Gotcha: Forgetting to register the OpenCage provider before use.
    • Fix: Always
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