### Minimal Geocoding Example Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/README.md Demonstrates basic forward and reverse geocoding using the Geocoder facade. Shows how to get coordinates and address details from a location, and how to convert coordinates back to an address. ```php use Geocoder\Laravel\Facades\Geocoder; // Geocode an address $results = Geocoder::geocode('Paris, France')->get(); $address = $results->first(); echo $address->getLatitude(); // 48.8566 echo $address->getLongitude(); // 2.3522 echo $address->getCountry()->getName(); // France // Reverse geocode coordinates $results = Geocoder::reverse(48.8566, 2.3522)->get(); echo $results->first()->getFormattedAddress(); // Paris, Île-de-France, France ``` -------------------------------- ### Configuration Example Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/module-reference.md Configure the HTTP adapter and providers in the `config/geocoder.php` file. ```php use Geocoder\Laravel\Http\LaravelHttpClient; use Geocoder\Provider\GoogleMaps\GoogleMaps; use Geocoder\Provider\Chain\Chain; // In config/geocoder.php 'adapter' => LaravelHttpClient::class, 'providers' => [ Chain::class => [ GoogleMaps::class => [env('GOOGLE_MAPS_LOCALE', 'us'), env('GOOGLE_MAPS_API_KEY')], ], ], ``` -------------------------------- ### Providers Configuration Example Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/README.md Define the geocoding providers to be used and their specific configurations, including API keys and locales. This allows for flexible provider selection and setup. ```php 'providers' => [ Chain::class => [ GoogleMaps::class => ['us', env('GOOGLE_MAPS_API_KEY')], Nominatim::class => ['MyApp/1.0'], GeoPlugin::class => [], ], ] ``` -------------------------------- ### Provider Structure Example Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/configuration.md Illustrates the general structure for configuring providers, showing how to pass constructor arguments. ```php 'providers' => [ ProviderClass::class => [ // Constructor arguments arg1, arg2, // ... ], // ... more providers ], ``` -------------------------------- ### Install Geocoder for Laravel Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/quick-start.md Install the package using Composer and publish the configuration file. ```bash composer require toin0u/geocoder-laravel php artisan vendor:publish --provider="Geocoder\Laravel\Providers\GeocoderService" --tag="config" ``` -------------------------------- ### Provider Configuration Array Example Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/types.md Illustrates how to configure providers in `config/geocoder.php`, specifying provider classes and their constructor arguments. ```php [ ProviderClass::class => [ // Constructor arguments 'arg1', 'arg2', ... ], ] ``` ```php [ Chain::class => [ GoogleMaps::class => [ 'us', // locale 'AIzaSyD...', // api_key ], GeoPlugin::class => [], ], ] ``` -------------------------------- ### Get Providers From Configuration Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/implementation-details.md Processes provider configuration to instantiate providers. It checks if a provider is already bound in the container, handles Chain providers with logger setup, and uses reflection for other providers. ```php protected function getProvidersFromConfiguration(Collection $providers): array { $providers = $providers->map(function ($arguments, $provider) { // 1. Check if provider is bound in container if (app()->bound($provider)) { return app($provider); } // 2. Get adapter and arguments $arguments = $this->getArguments($arguments, $provider); $reflection = new ReflectionClass($provider); // 3. Handle Chain provider specially (logger setup) if ($provider === "Geocoder\Provider\Chain\Chain") { $chainProvider = $reflection->newInstance($arguments); if (class_exists(Logger::class) && in_array(LoggerAwareTrait::class, class_uses($chainProvider)) && app(Logger::class) !== null ) { $chainProvider->setLogger(app(Logger::class)); } return $chainProvider; } // 4. Instantiate provider with reflection return $reflection->newInstanceArgs($arguments); }); return $providers->toArray(); } ``` -------------------------------- ### Using php-http/curl-client Adapter Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/configuration.md Configure the adapter to use php-http/curl-client. Ensure the package is installed via composer. ```bash composer require php-http/curl-client ``` ```php use Http\Client\Curl\Client; 'adapter' => [Client::class => [ null, // curl handle null, // curl options object [CURLOPT_PROXY => env('CURL_PROXY')], // CURL options ]], ``` -------------------------------- ### Adapter Configuration Array Example Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/types.md Shows the structure for configuring adapters in `config/geocoder.php`, including timeout, connection timeout, retry settings, and options. ```php [ AdapterClass::class => [ // Constructor arguments 'timeout' => 10, 'connectTimeout' => 3, 'retry' => [3, 100], 'options' => [], ], ] ``` -------------------------------- ### Initialize ProviderAndDumperAggregator Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/api-reference/provider-and-dumper-aggregator.md Initializes a new ProviderAndDumperAggregator instance. This is the starting point for using the geocoder service. ```php public function __construct() ``` ```php $geocoder = new ProviderAndDumperAggregator(); ``` -------------------------------- ### Cache Configuration Example Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/README.md Configure cache settings like the store, duration, and serialization for security. This is useful for controlling how geocoding results are cached. ```php 'cache' => [ 'store' => 'redis', 'duration' => 86400, 'auto_register_serializable_classes' => true, ] ``` -------------------------------- ### Example Output of Discovered Serializable Classes Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/api-reference/geocoder-service-provider.md Illustrates the typical output format when the service provider discovers all geocoder model classes from installed vendor packages. This list is used to update Laravel's cache configuration. ```php [ 'Illuminate\Support\Collection', 'Geocoder\Model\Address', 'Geocoder\Model\Coordinates', 'Geocoder\Model\Country', 'Geocoder\Model\Province', // ... more classes ] ``` -------------------------------- ### Adapter Configuration Example Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/README.md Configure the HTTP client adapter, specifying timeouts, connection timeouts, and retry strategies. This is essential for managing network requests to geocoding services. ```php 'adapter' => [LaravelHttpClient::class => [ 'timeout' => 10, 'connectTimeout' => 3, 'retry' => [3, 100], ]], ``` -------------------------------- ### Example Usage in register() Method Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/api-reference/geocoder-service-provider.md Demonstrates how to access and potentially customize the Geocoder service within the 'register' method of a custom service provider. The geocoder service is available for use after this method is called. ```php public function register() { // Custom setup // The geocoder service is available now } ``` -------------------------------- ### GoogleMaps Provider Configuration with Locale Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/configuration.md Example of configuring the Google Maps provider with a specific locale ('it') and API key. ```php use Geocoder\Provider\GoogleMaps\GoogleMaps; use Geocoder\Provider\Chain\Chain; 'providers' => [ Chain::class => [ GoogleMaps::class => [ 'it', // Locale env('GOOGLE_MAPS_API_KEY'), ], ], ], ``` -------------------------------- ### Method Chaining Example Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/api-reference/provider-and-dumper-aggregator.md Demonstrates chaining multiple methods to configure and execute a geocoding query. Use this to set locale, limit results, disable caching, and perform the geocode operation. ```php $results = app('geocoder') ->locale('it') ->limit(3) ->doNotCache() ->geocode('Venice') ->get(); ``` -------------------------------- ### Complete Configuration Example Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/configuration.md This snippet shows a comprehensive configuration for the Geocoder Laravel package, including cache settings, a chain of providers (Google Maps, Nominatim, GeoPlugin), and an HTTP adapter with retry logic. ```php [ 'store' => 'geocode', // Use dedicated cache store 'duration' => 86400, // Cache for 24 hours 'auto_register_serializable_classes' => true, ], // Providers in chain order 'providers' => [ Chain::class => [ // Primary: GoogleMaps with API key GoogleMaps::class => [ env('GOOGLE_MAPS_LOCALE', 'us'), env('GOOGLE_MAPS_API_KEY'), ], // Fallback: Nominatim (OpenStreetMap) Nominatim::class => [ 'MyApplication/1.0', // User agent ], // Last resort: GeoPlugin (free, no API key) GeoPlugin::class => [], ], ], // HTTP adapter with timeouts and retries 'adapter' => [LaravelHttpClient::class => [ 'timeout' => 10, // 10 second request timeout 'connectTimeout' => 3, // 3 second connection timeout 'retry' => [2, 100], // 2 retries, 100ms delay ]], // Reader for GeoIP2 (if using that provider) 'reader' => null, ]; ``` -------------------------------- ### Configuration File Reference Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/quick-start.md The config/geocoder.php file automatically utilizes environment variables for configuration, simplifying setup. ```php // config/geocoder.php automatically uses env() values ``` -------------------------------- ### Configure Multiple Geocoding Providers Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/quick-start.md Set up multiple providers in the configuration file to create a fallback chain. Examples include Google Maps, Nominatim, and GeoPlugin. ```php // config/geocoder.php use Geocoder\Provider\Chain\Chain; use Geocoder\Provider\GoogleMaps\GoogleMaps; use Geocoder\Provider\Nominatim\Nominatim; use Geocoder\Provider\GeoPlugin\GeoPlugin; 'providers' => [ Chain::class => [ GoogleMaps::class => ['us', env('GOOGLE_MAPS_API_KEY')], Nominatim::class => ['MyApp/1.0'], GeoPlugin::class => [], ], ], // In code, use specific provider: $google = Geocoder::using('google_maps')->geocode('Paris')->get(); ``` -------------------------------- ### Switch to Alternative HTTP Client (Curl) Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/api-reference/laravel-http-client.md Configures Geocoder to use an alternative HTTP client, such as php-http/curl-client. Ensure the alternative adapter is installed via Composer. This example shows how to pass CURL options. ```php use Http\Client\Curl\Client; 'adapter' => [Client::class => [ null, // curl options object null, // curl options object [CURLOPT_PROXY => env('CURL_PROXY')], // CURL options array ]], ``` -------------------------------- ### Install geocoder-laravel Package Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/README.md Install the package using Composer. This is the initial step for integrating geocoding capabilities into your Laravel application. ```sh composer require toin0u/geocoder-laravel ``` -------------------------------- ### Use GeocodeQuery with Geocoder Service Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/types.md Shows how to construct a GeocodeQuery with locale and limit, and then use it with the Geocoder service to get results. ```php use Geocoder\Query\GeocodeQuery; $query = GeocodeQuery::create('Milan') ->withLocale('it') ->withLimit(3); $results = app('geocoder')->geocodeQuery($query)->get(); ``` -------------------------------- ### Configure File Cache for Geocoding Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/configuration.md Example of configuring the Geocoder package to use the file-based cache store. ```php 'cache' => [ 'store' => 'file', ], ``` -------------------------------- ### Cache Configuration Array Example Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/types.md Defines the configuration for caching in `config/geocoder.php`, specifying the cache store, duration, and whether to auto-register serializable classes. ```php [ 'store' => 'redis', 'duration' => 86400, 'auto_register_serializable_classes' => true, ] ``` -------------------------------- ### Production Configuration Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/configuration.md This configuration is optimized for production, utilizing Redis for caching with a long duration and a robust HTTP adapter setup including retries. ```php 'cache' => [ 'duration' => 2592000, // 30 days 'store' => 'redis', // Redis for performance 'auto_register_serializable_classes' => true, ], 'adapter' => [LaravelHttpClient::class => [ 'timeout' => 10, 'connectTimeout' => 3, 'retry' => [3, 100], ]], ``` -------------------------------- ### Add Composer Post-Update/Install Commands Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/README.md Add these commands to your composer.json to automatically clear the cache after package updates or installations, ensuring fresh data. ```json "post-update-cmd": [ "@php artisan cache:clear", ], "post-install-cmd": [ "@php artisan cache:clear", ] ``` -------------------------------- ### Fluent Method Chaining for Geocoding Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/module-reference.md Demonstrates how to chain multiple methods for geocoding requests, starting with locale and limit, then performing the geocode operation and retrieving results. Most methods return 'self' to enable this fluent interface. ```php $results = app('geocoder') ->locale('it') // Returns self ->limit(3) // Returns self ->doNotCache() // Returns self ->geocode('Rome') // Returns self ->get(); // Returns Collection ``` -------------------------------- ### Configure Dedicated Redis Cache for Geocoding Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/configuration.md Example of setting up a dedicated Redis cache store for geocoding results. This involves configuring the cache store in `config/geocoder.php`, `config/cache.php`, and `config/database.php`. ```php // config/geocoder.php 'cache' => [ 'store' => 'geocode', // Custom redis store for geocoding only ], // config/cache.php 'stores' => [ 'geocode' => [ 'driver' => 'redis', 'connection' => 'geocode-cache', ], ], // config/database.php 'redis' => [ 'geocode-cache' => [ 'host' => env('REDIS_HOST', '127.0.0.1'), 'password' => env('REDIS_PASSWORD', null), 'port' => env('REDIS_PORT', 6379), 'database' => 1, // Separate database for geocoding ], ], ``` -------------------------------- ### Locating Address Class File with Reflection Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/implementation-details.md Uses ReflectionClass to get the file name of the Address class, which can be used for locating the vendor directory for serializable class discovery. ```php $addressFile = (new ReflectionClass(Address::class))->getFileName(); ``` -------------------------------- ### Get Provider Arguments with Adapter Injection Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/implementation-details.md Retrieves constructor arguments for a provider, injecting an HTTP adapter if required. It handles the Chain provider separately and builds the adapter instance based on configuration. ```php protected function getArguments(array $arguments, string $provider): array { // Chain provider doesn't need adapter if ($provider === 'Geocoder\Provider\Chain\Chain') { return $this->getProvidersFromConfiguration( collect(config('geocoder.providers.Geocoder\Provider\Chain\Chain')) ); } // Get adapter class for this provider $adapter = $this->getAdapterClass($provider); if ($adapter) { // Build adapter instance with constructor args if ($this->requiresReader($provider)) { $adapter = new $adapter($this->getReader()); } else { $adapter = $this->buildAdapter($adapter); } // Prepend adapter to provider constructor arguments array_unshift($arguments, $adapter); } return $arguments; } ``` -------------------------------- ### Service Container Binding Examples Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/api-reference/provider-and-dumper-aggregator.md Shows different ways to access the geocoder service using Laravel's service container. You can use the facade, the container directly, or dependency injection. ```php // Via facade Geocoder::geocode('Paris')->get(); ``` ```php // Via container app('geocoder')->geocode('Paris')->get(); ``` ```php // Via dependency injection public function show(ProviderAndDumperAggregator $geocoder) { $results = $geocoder->geocode('Paris')->get(); } ``` -------------------------------- ### Provider Instantiation with Reflection Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/implementation-details.md Shows how to dynamically instantiate providers using PHP's Reflection API, specifically ReflectionClass::newInstanceArgs(). ```php $reflection = new ReflectionClass($provider); $instance = $reflection->newInstanceArgs($arguments); ``` -------------------------------- ### Facade vs. Direct Usage Comparison Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/api-reference/geocoder-facade.md Illustrates the equivalence between using the Geocoder facade, the container helper, and dependency injection for accessing the geocoder service. ```php // Via facade Geocoder::geocode('Paris')->get(); // Via container helper app('geocoder')->geocode('Paris')->get(); // Via dependency injection public function search(ProviderAndDumperAggregator $geocoder) { return $geocoder->geocode('Paris')->get(); } ``` -------------------------------- ### Get Coordinates from Address Object Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/types.md Extract latitude and longitude from a Coordinates object, which is obtained from an Address object. This snippet shows how to get the specific latitude and longitude values. ```php $results = app('geocoder')->geocode('Rome')->get(); $coords = $results->first()->getCoordinates(); echo $coords->getLatitude(); // 41.9028 echo $coords->getLongitude(); // 12.4964 ``` -------------------------------- ### Geocode IP Address Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/README.md Get information for a given IP address. ```php app('geocoder')->geocode('8.8.8.8')->get(); ``` -------------------------------- ### Geocode Address Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/README.md Get a collection of addresses for a given location string. ```php app('geocoder')->geocode('Los Angeles, CA')->get(); ``` -------------------------------- ### Reverse Geocode Coordinates Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/README.md Get an address for a given set of latitude and longitude coordinates. ```php app('geocoder')->reverse(43.882587,-103.454067)->get(); ``` -------------------------------- ### Boot Service Provider Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/implementation-details.md This method is executed after all service providers are registered. It handles publishing the configuration file, merging default configurations, and registering serializable classes for newer Laravel versions. ```php public function boot(): void { // 1. Publish configuration file $configPath = __DIR__ . "/../../config/geocoder.php"; $this->publishes([$configPath => $this->configPath("geocoder.php")], "config"); // 2. Merge default configuration $this->mergeConfigFrom($configPath, "geocoder"); // 3. Register serializable classes (Laravel 13+) $this->registerSerializableClasses(); } ``` -------------------------------- ### Get the Current Result Limit Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/api-reference/provider-and-dumper-aggregator.md Retrieves the current limit set for the number of geocoding results to be returned. ```php $limit = app('geocoder')->getLimit(); ``` -------------------------------- ### Disable Global Geocoding Caching Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/configuration.md Example of disabling all geocoding caching by setting the cache duration to 0. ```php 'cache' => [ 'duration' => 0, // No caching ], ``` -------------------------------- ### Using the Facade Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/module-reference.md Import and use the Geocoder facade to perform geocoding operations. ```php use Geocoder\Laravel\Facades\Geocoder; Geocoder::geocode('Paris')->get(); ``` -------------------------------- ### Set Connection Establishment Timeout Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/api-reference/laravel-http-client.md Configure the maximum time in seconds to wait for a TCP connection to be established. Defaults to no connection timeout. ```php 'adapter' => [LaravelHttpClient::class => ['connectTimeout' => 3]], ``` -------------------------------- ### getName(): string Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/api-reference/provider-and-dumper-aggregator.md Gets the name of the currently active provider from the ProviderAggregator. The name is typically a string identifier like 'chain'. ```APIDOC ## getName(): string ### Description Gets the name of the currently active provider from the ProviderAggregator. ### Parameters None ### Return type `string` — Provider name (e.g., 'chain') ### Example ```php echo app('geocoder')->getName(); ``` ``` -------------------------------- ### get(): Collection Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/api-reference/provider-and-dumper-aggregator.md Returns the results of the last geocoding/reverse geocoding query as a Laravel Collection. Each item in the collection is an Address object. ```APIDOC ## get(): Collection ### Description Returns the results of the last geocoding/reverse geocoding query as a Laravel Collection. ### Return type `Illuminate\Support\Collection` — Collection of `Geocoder\Model\Address` objects ### Example ```php $results = app('geocoder')->geocode('London')->get(); foreach ($results as $address) { echo $address->getStreetNumber(); echo $address->getStreetName(); echo $address->getCountry()->getName(); } ``` ``` -------------------------------- ### Class Constructor Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/api-reference/provider-and-dumper-aggregator.md Initializes a new ProviderAndDumperAggregator instance with an internal ProviderAggregator and empty results collection. ```APIDOC ## Class Constructor ### Description Initializes a new ProviderAndDumperAggregator instance with an internal ProviderAggregator and empty results collection. ### Parameters None ### Return type `ProviderAndDumperAggregator` ### Example ```php $geocoder = new ProviderAndDumperAggregator(); ``` ``` -------------------------------- ### Create GeocodeQuery Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/types.md Demonstrates creating a GeocodeQuery for forward geocoding with different options like locale and limit. ```php use Geocoder\Query\GeocodeQuery; $query = GeocodeQuery::create('Paris, France'); $query = GeocodeQuery::create('Paris')->withLocale('fr'); $query = GeocodeQuery::create('Paris')->withLimit(5); ``` -------------------------------- ### Build HTTP Adapter Instance Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/implementation-details.md Constructs an HTTP adapter instance. If the adapter has specific constructor arguments defined in the configuration, they are used; otherwise, the adapter is resolved from the container. ```php protected function buildAdapter(string $class) { $adapterConfig = config('geocoder.adapter'); if (is_array($adapterConfig) && isset($adapterConfig[$class])) { // Has constructor arguments $reflection = new ReflectionClass($class); return $reflection->newInstanceArgs($adapterConfig[$class]); } // No arguments, resolve from container return app($class); } ``` -------------------------------- ### Get All Registered Providers Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/api-reference/provider-and-dumper-aggregator.md Retrieves all registered providers within the aggregator as a Laravel Collection. This allows iteration over all available provider instances. ```php $providers = app('geocoder')->getProviders(); foreach ($providers as $provider) { echo $provider->getName(); } ``` -------------------------------- ### Usage Pattern for Geocoder Facade Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/api-reference/geocoder-facade.md Demonstrates the basic static usage of the Geocoder facade for geocoding, reverse geocoding, and setting locale. ```php use Geocoder\Laravel\Facades\Geocoder; // All methods proxy to the ProviderAndDumperAggregator Geocoder::geocode('Paris')->get(); Geocoder::reverse(48.8566, 2.3522)->get(); Geocoder::locale('fr')->geocode('Lyon')->get(); ``` -------------------------------- ### Get the Name of the Active Provider Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/api-reference/provider-and-dumper-aggregator.md Retrieves the name of the currently active provider within the aggregator. This is typically 'chain' if multiple providers are configured. ```php echo app('geocoder')->getName(); ``` -------------------------------- ### Registering Providers Requiring Static Factories Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/configuration.md Shows how to register a provider like Nominatim that uses a static factory method with OpenStreetMap server in AppServiceProvider. ```php // app/Providers/AppServiceProvider.php use Geocoder\Provider\Nominatim\Nominatim; use Geocoder\Laravel\Http\LaravelHttpClient; public function register() { $this->app->bind(Nominatim::class, fn ($app) => Nominatim::withOpenStreetMapServer( $app->make(LaravelHttpClient::class), 'MyApp/1.0' ) ); } // config/geocoder.php 'providers' => [ Nominatim::class => [], // Uses bound instance from container ], ``` -------------------------------- ### Set Geocoding Cache Duration to 24 Hours Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/configuration.md Example of setting the cache duration for geocoding results to 24 hours (86400 seconds). ```php 'cache' => [ 'duration' => 86400, // 24 hours ], ``` -------------------------------- ### Using Dependency Injection Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/module-reference.md Inject the ProviderAndDumperAggregator service to perform geocoding within your classes. ```php use Geocoder\Laravel\ProviderAndDumperAggregator; public function locate(ProviderAndDumperAggregator $geocoder) { $results = $geocoder->geocode('Paris')->get(); } ``` -------------------------------- ### LaravelHttpClient Constructor and Configuration Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/module-reference.md Illustrates how to instantiate `LaravelHttpClient` with custom timeout, connection timeout, retry settings, and additional Guzzle options. Also shows configuration via `config/geocoder.php`. ```php use Geocoder\Laravel\Http\LaravelHttpClient; $client = new LaravelHttpClient( timeout: 10, connectTimeout: 3, retry: [3, 100], ); // Or via config/geocoder.php 'adapter' => [LaravelHttpClient::class => [ 'timeout' => 10, 'connectTimeout' => 3, 'retry' => [3, 100], ]], ``` -------------------------------- ### Accessing the Geocoder Service Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/api-reference/geocoder-service-provider.md Demonstrates various ways to access the geocoder service after the service provider has booted: via the container, using the facade, or through dependency injection. Ensure the service provider is registered. ```php // Via container $geocoder = app('geocoder'); ``` ```php // Via facade use Geocoder\Laravel\Facades\Geocoder; Geocoder::geocode('Paris')->get(); ``` ```php // Via dependency injection use Geocoder\Laravel\ProviderAndDumperAggregator; public function locate(ProviderAndDumperAggregator $geocoder) { return $geocoder->geocode('London')->get(); } ``` -------------------------------- ### Accessing ProviderAndDumperAggregator Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/module-reference.md Demonstrates how to obtain an instance of `ProviderAndDumperAggregator` using Laravel's container or through dependency injection. ```php use Geocoder\Laravel\ProviderAndDumperAggregator; // Container binding $geocoder = app('geocoder'); // Or $geocoder = app(ProviderAndDumperAggregator::class); // Dependency injection public function locate(ProviderAndDumperAggregator $geocoder) { $results = $geocoder->geocode('Paris')->get(); } ``` -------------------------------- ### Get Geocoding Results as Collection Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/api-reference/provider-and-dumper-aggregator.md Retrieves the results of the last geocoding or reverse geocoding query as a Laravel Collection. Each item in the collection is an Address object. ```php $results = app('geocoder')->geocode('London')->get(); foreach ($results as $address) { echo $address->getStreetNumber(); echo $address->getStreetName(); echo $address->getCountry()->getName(); } ``` -------------------------------- ### Create ReverseQuery Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/types.md Illustrates creating a ReverseQuery for reverse geocoding using coordinates, with options for locale and limit. ```php use Geocoder\Query\ReverseQuery; $query = ReverseQuery::fromCoordinates(48.8566, 2.3522); $query = ReverseQuery::fromCoordinates(48.8566, 2.3522)->withLocale('fr'); $query = ReverseQuery::fromCoordinates(48.8566, 2.3522)->withLimit(3); ``` -------------------------------- ### Get the Currently Active Provider Instance Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/api-reference/provider-and-dumper-aggregator.md Retrieves the instance of the currently active provider from the ProviderAggregator. If no provider is explicitly set, it returns the first provider in the chain. ```php $provider = app('geocoder')->getProvider(); echo $provider->getName(); ``` -------------------------------- ### Using a Specific Provider Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/configuration.md Demonstrates how to bypass the Chain provider and use a specific provider, Google Maps, directly. ```php // Use GoogleMaps specifically, skipping the chain $results = app('geocoder') ->using('google_maps') ->geocode('Paris') ->get(); ``` -------------------------------- ### Working with Query Objects Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/module-reference.md Create query objects for geocoding and reverse geocoding. ```php use Geocoder\Query\GeocodeQuery; use Geocoder\Query\ReverseQuery; $query = GeocodeQuery::create('Paris'); $query = ReverseQuery::fromCoordinates(48.8566, 2.3522); ``` -------------------------------- ### Access Geocoder via Facade Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/README.md Demonstrates using the static Geocoder facade for convenient access to geocoding functionality. ```php use Geocoder\Laravel\Facades\Geocoder; $results = Geocoder::geocode('London')->get(); ``` -------------------------------- ### Development Configuration Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/configuration.md This configuration is optimized for development, using a file-based cache with a shorter duration for faster iteration and a more generous HTTP timeout for debugging. ```php 'cache' => [ 'duration' => 3600, // 1 hour for faster iteration 'store' => 'file', // File-based cache for simplicity ], 'adapter' => [LaravelHttpClient::class => [ 'timeout' => 30, // Generous timeout for debugging ]], ``` -------------------------------- ### Mocking Geocoder Facade in Tests Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/api-reference/geocoder-facade.md Demonstrates how to mock the Geocoder facade using Laravel's testing utilities to simulate geocoding responses. ```php use Geocoder\Laravel\Facades\Geocoder; public function test_geocoding() { Geocoder::shouldReceive('geocode') ->with('Paris') ->andReturn(collect([ // mock address objects ])); $results = Geocoder::geocode('Paris')->get(); $this->assertEquals(1, $results->count()); } ``` -------------------------------- ### Configure Redis Cache Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/configuration.md Configure Redis connection details if the cache store is set to 'redis'. This includes host, password, and port. ```bash REDIS_HOST=127.0.0.1 REDIS_PASSWORD=null REDIS_PORT=6379 ``` -------------------------------- ### Enable Automatic Serializable Classes Registration (Default) Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/configuration.md Example showing the default configuration for `auto_register_serializable_classes`, which is `true`. This ensures Geocoder model classes are automatically registered for safe deserialization in Laravel 13+. ```php 'cache' => [ 'auto_register_serializable_classes' => true, ], ``` -------------------------------- ### Get Country Name and Code from Address Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/types.md Retrieve the full country name and its ISO 3166-1 alpha-2 code from a Country object, which is part of an Address object. This is useful for displaying or processing country-specific information. ```php $country = $results->first()->getCountry(); echo $country->getName(); // "France" echo $country->getCode(); // "FR" ``` -------------------------------- ### Use ReverseQuery with Geocoder Service Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/types.md Demonstrates creating a ReverseQuery with specific coordinates, locale, and limit, and then using it with the Geocoder service. ```php use Geocoder\Query\ReverseQuery; $query = ReverseQuery::fromCoordinates(48.8566, 2.3522) ->withLocale('fr') ->withLimit(1); $results = app('geocoder')->reverseQuery($query)->get(); ``` -------------------------------- ### Disable Automatic Serializable Classes and Manage Manually Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/configuration.md Example of disabling `auto_register_serializable_classes` and manually managing the `cache.serializable_classes` allow-list in Laravel's cache configuration. This is useful for explicit control or when not using Laravel 13+. ```php // config/geocoder.php 'cache' => [ 'auto_register_serializable_classes' => false, ], // config/cache.php 'serializable_classes' => [ 'Geocoder\Model\Address', 'Geocoder\Model\Coordinates', 'Geocoder\Model\Country', 'Geocoder\Model\Province', 'Illuminate\Support\Collection', // ... add any custom classes ], ``` -------------------------------- ### Mocking Invalid Dumper Exception in Geocoder Laravel Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/errors.md This example shows how to mock an InvalidDumperException to test scenarios where an unsupported dumper format is requested. It ensures your application correctly handles errors related to data dumping. ```php use Geocoder\Laravel\Exceptions\InvalidDumperException; public function test_invalid_dumper_throws_exception() { $geocoder = app('geocoder'); $this->expectException(InvalidDumperException::class); $geocoder->geocode('Paris')->dump('xml')->get(); } ``` -------------------------------- ### Configure CurlHttpClient Adapter with Proxy Options Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/README.md Use the CurlHttpClient adapter and pass CURL options, such as proxy settings, via the configuration. ```php 'adapter' => [Http\Client\Curl\Client::class => [ null, null, [CURLOPT_PROXY => env('CURL_PROXY'), CURLOPT_PROXYUSERPWD => env('CURL_PROXYUSERPWD')], ]], ``` -------------------------------- ### Search Address and Return JSON Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/quick-start.md Implement a route to accept an address, geocode it, limit the results, and return them as a JSON response. Includes basic error handling. ```php Route::post('/geocode', function (Request $request) { try { $results = Geocoder::geocode($request->input('address')) ->limit(5) ->get(); return response()->json([ 'count' => $results->count(), 'results' => $results->map(fn($a) => [ 'lat' => $a->getLatitude(), 'lng' => $a->getLongitude(), 'address' => $a->getFormattedAddress(), ])->toArray(), ]); } catch (Exception $e) { return response()->json(['error' => 'Geocoding failed'], 500); } }); ``` -------------------------------- ### Get Address Details from Geocoding Query Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/types.md Retrieve address details and coordinates for a given location. The Address object provides methods to access latitude, longitude, country, city, postal code, and the fully formatted address. ```php $results = app('geocoder')->geocode('Paris, France')->get(); $address = $results->first(); $latitude = $address->getLatitude(); // 48.8566 $longitude = $address->getLongitude(); // 2.3522 $country = $address->getCountry(); // Country object $city = $address->getLocality(); // "Paris" $zip = $address->getPostalCode(); // "75000" $formatted = $address->getFormattedAddress(); // "Paris, Île-de-France, France" ``` -------------------------------- ### using(string $name): self Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/api-reference/provider-and-dumper-aggregator.md Switches to a specific named provider from the provider chain. The provider name is typically the class name without the namespace. This method allows for fluent chaining. ```APIDOC ## using(string $name): self ### Description Switches to a specific named provider from the provider chain. The provider name is typically the class name without the namespace. ### Parameters #### Path Parameters - **name** (string) - Required - The provider name/alias ### Return type `self` — Returns the instance for method chaining ### Example ```php $results = app('geocoder')->using('google_maps')->geocode('Rome')->get(); ``` ``` -------------------------------- ### Register Providers from Configuration Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/api-reference/provider-and-dumper-aggregator.md Registers providers based on a configuration collection, typically loaded from config/geocoder.php. It handles instantiation with arguments, adapters, readers, and loggers. ```php app('geocoder')->registerProvidersFromConfig($providers); ``` -------------------------------- ### Private Property Access with Reflection Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/implementation-details.md Demonstrates accessing private properties of a class using ReflectionClass and ReflectionProperty, including setting accessibility. ```php $reflectedClass = new ReflectionClass(ProviderAggregator::class); $reflectedProperty = $reflectedClass->getProperty('provider'); $reflectedProperty->setAccessible(true); return $reflectedProperty->getValue($this->aggregator); ``` -------------------------------- ### ProviderAndDumperAggregator Public Methods Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/module-reference.md Lists the public methods available on the `ProviderAndDumperAggregator` class for geocoding, configuration, result retrieval, and introspection. ```php // Geocoding public function geocode(string $value): self public function reverse(float $latitude, float $longitude): self public function geocodeQuery(GeocodeQuery $query): self public function reverseQuery(ReverseQuery $query): self // Configuration public function locale(?string $locale): self public function doNotCache(): self public function limit(int $limit): self public function using(string $name): self // Results public function get(): Collection public function all(): array // Deprecated public function dump(string $dumper): Collection public function toJson(): string // Introspection public function getName(): string public function getLimit(): int public function getProvider() public function getProviders(): Collection public function registerProvider($provider): self public function registerProviders(array $providers = []): self public function registerProvidersFromConfig(Collection $providers): self ``` -------------------------------- ### Create New Geocoder Instance Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/implementation-details.md When using asynchronous frameworks like ReactPHP or Amphp, ensure you create a new instance of ProviderAndDumperAggregator per coroutine instead of sharing a singleton. This avoids thread safety issues with request-scoped properties. ```php registerProvidersFromConfig(collect(config('geocoder.providers'))); ``` -------------------------------- ### Mocking Geocoder Service via Container Binding Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/api-reference/geocoder-facade.md Shows an alternative testing approach by binding a mocked ProviderAndDumperAggregator instance to the 'geocoder' container key. ```php public function test_geocoding() { $mock = Mockery::mock(ProviderAndDumperAggregator::class); $mock->shouldReceive('geocode')->with('Paris')->andReturn( $mock ); $mock->shouldReceive('get')->andReturn(collect([])); $this->app->bind('geocoder', $mock); // Your test code here } ``` -------------------------------- ### Configuring LaravelHttpClient in geocoder.php (Simple) Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/api-reference/laravel-http-client.md Shows the basic configuration for using LaravelHttpClient as a Geocoder adapter in the `config/geocoder.php` file, relying on default constructor arguments. ```php 'adapter' => LaravelHttpClient::class, ``` -------------------------------- ### Checking for Nullable Address Properties Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/types.md Demonstrates how to check if address properties like country, postal code, and timezone are available before using them. Always perform null checks to avoid errors. ```php $address = $results->first(); if ($address->getCountry()) { // Country is available } $zip = $address->getPostalCode(); // May be null $timezone = $address->getTimezone(); // May be null ``` -------------------------------- ### Geocoder Facade Usage Source: https://github.com/geocoder-php/geocoderlaravel/blob/master/_autodocs/module-reference.md Shows how to use the `Geocoder` facade to perform geocoding and reverse geocoding operations. ```php use Geocoder\Laravel\Facades\Geocoder; Geocoder::geocode('Paris')->get(); Geocoder::reverse(48.8566, 2.3522)->get(); ```