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

Geocoder Laravel Package

spatie/geocoder

Convert any address into GPS coordinates in Laravel/PHP using Google’s Geocoding API. Simple facade-based calls return lat/lng plus accuracy, formatted address, and viewport data. Ideal for mapping, location search, and address validation.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/geocoder
    

    Publish the config file:

    php artisan vendor:publish --provider="Spatie\Geocoder\GeocoderServiceProvider"
    
  2. Configure API Key: Edit config/geocoder.php and add your Google Maps API key under services.google_maps:

    'google_maps' => [
        'key' => env('GOOGLE_MAPS_API_KEY'),
    ],
    

    Set the key in your .env:

    GOOGLE_MAPS_API_KEY=your_api_key_here
    
  3. First Use Case: Geocode an address in a controller or service:

    use Spatie\Geocoder\Facades\Geocoder;
    
    $coordinates = Geocoder::getCoordinatesForAddress('1600 Amphitheatre Parkway, Mountain View, CA');
    // Returns: ['lat' => 37.422..., 'lng' => -122.084...]
    

Key Starting Points

  • Facade: Use Geocoder:: for quick access to methods.
  • Service Container: Bind custom geocoders via GeocoderServiceProvider.
  • Models: Use traits like HasCoordinates for Eloquent models.

Implementation Patterns

Core Workflows

  1. Geocoding Addresses:

    // Basic geocoding
    $coordinates = Geocoder::getCoordinatesForAddress('Address, City, Country');
    
    // With fallback to multiple providers
    $coordinates = Geocoder::withFallbackTo([
        'google_maps',
        'openstreetmaps',
    ])->getCoordinatesForAddress('Address');
    
  2. Reverse Geocoding:

    $address = Geocoder::getAddressForCoordinates(37.422, -122.084);
    
  3. Model Integration: Use the HasCoordinates trait to auto-geocode addresses on model save:

    use Spatie\Geocoder\HasCoordinates;
    
    class Location extends Model
    {
        use HasCoordinates;
    
        protected $geocodable = 'address';
    }
    

    Then call:

    $location = new Location(['address' => '123 Main St']);
    $location->geocode(); // Automatically populates lat/lng
    
  4. Batch Processing:

    $addresses = ['Address 1', 'Address 2'];
    $coordinates = Geocoder::getCoordinatesForAddresses($addresses);
    

Integration Tips

  • Caching: Cache results to avoid API rate limits:
    $coordinates = Geocoder::getCoordinatesForAddress('Address')->remember(60 * 24);
    
  • Custom Providers: Extend Spatie\Geocoder\Geocoder to add new providers.
  • Validation: Validate addresses before geocoding (e.g., using spatie/laravel-address).
  • Queue Jobs: Offload geocoding to queues for large datasets:
    Geocoder::getCoordinatesForAddress('Address')->onQueue('geocoding');
    

Gotchas and Tips

Common Pitfalls

  1. API Key Restrictions:

    • Google Maps API keys may have usage restrictions (e.g., no billing for certain use cases).
    • Fix: Use the billing key type in Google Cloud Console or switch to free alternatives like OpenStreetMap.
  2. Rate Limits:

    • Google Maps API has usage limits.
    • Fix: Cache results aggressively or use fallback providers.
  3. Address Ambiguity:

    • Ambiguous addresses (e.g., "Springfield") may return unexpected results.
    • Fix: Append city/country or use getCoordinatesForAddressWithFallback().
  4. Model Trait Conflicts:

    • HasCoordinates may conflict with other traits or model events.
    • Fix: Override geocode() or use explicit calls like $model->geocodeNow().
  5. Timeouts:

    • Slow responses from external APIs can time out.
    • Fix: Increase PHP timeout or use async processing.

Debugging Tips

  • Log Responses: Enable debug mode in config/geocoder.php:

    'debug' => env('GEOCODER_DEBUG', false),
    

    Logs will appear in storage/logs/geocoder.log.

  • Check HTTP Status: Inspect the response property of the returned object:

    $coordinates = Geocoder::getCoordinatesForAddress('Address');
    if ($coordinates->hasError()) {
        log($coordinates->getMessage());
    }
    

Extension Points

  1. Custom Geocoder: Create a new provider by extending Spatie\Geocoder\Geocoder:

    class CustomGeocoder extends Geocoder
    {
        public function getName()
        {
            return 'custom_provider';
        }
    
        public function getCoordinates($address)
        {
            // Custom logic
        }
    }
    

    Register it in config/geocoder.php:

    'providers' => [
        'custom_provider' => \App\Services\CustomGeocoder::class,
    ],
    
  2. Override Default Behavior: Bind your own geocoder instance in a service provider:

    $app->bind(\Spatie\Geocoder\Geocoder::class, function ($app) {
        return new \App\Services\CustomGeocoder();
    });
    
  3. Event Listeners: Listen for geocoding events (e.g., Geocoded, GeocodingFailed) via Laravel's event system.

Performance Optimizations

  • Batch Geocoding: Use getCoordinatesForAddresses() instead of looping.
  • Database Indexing: Ensure lat/lng columns are indexed for spatial queries.
  • Spatial Queries: Use Laravel Scout or spatie/laravel-scout-tntsearch for geospatial searches.
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport