maarheeze / geocode-laravel
laravel integration for maarheeze/geocode
Requires
- php: ^8.3
- illuminate/contracts: ^13.0
- illuminate/database: ^13.0
- illuminate/support: ^13.0
- maarheeze/geocode: ^1.0
- webmozart/assert: ^2.0
Requires (Dev)
- maarheeze/phpcs: ^1.0
- orchestra/testbench: ^11.0
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^12
README
Laravel integration for maarheeze/geocode.
This package wires the tiny, typed geocode library into Laravel: it binds the Geocode service in the container from config, ships a facade, and an optional database cache so repeated lookups don't hit the Google Maps API again.
Installation
composer require maarheeze/geocode-laravel
The package auto-registers via Laravel's package discovery, but make sure you run the migrations if you enable caching.
Configuration
Set your Google Maps API key:
GEOCODE_GOOGLE_MAPS_API_KEY=your-key
And you might want to override these default settings:
GEOCODE_CACHE_ENABLED=true GEOCODE_CACHE_TABLE=geocode_cache
Usage
The Maarheeze\Geocode\Geocode contract is bound in the container, so inject it anywhere:
use Maarheeze\Geocode\Geocode; class StoreController { public function __construct( private readonly Geocode $geocode, ) { } public function show(): void { $coordinates = $this->geocode->getCoordinatesForAddress('Stationsstraat 1, Maarheeze'); if ($coordinates !== null) { // $coordinates->latitude, $coordinates->longitude } } }
Or via the facade:
use Maarheeze\Geocode\Laravel\Facades\Geocode; $coordinates = Geocode::getCoordinatesForAddress('Stationsstraat 1, Maarheeze');
Distance
Coordinates can measure the great-circle distance to another Coordinates, returning a Distance you can read in meters or kilometers:
use Maarheeze\Geocode\Laravel\Facades\Geocode; $eindhoven = Geocode::getCoordinatesForAddress('Eindhoven'); $maarheeze = Geocode::getCoordinatesForAddress('Maarheeze'); if ($eindhoven === null || $maarheeze === null) { // One of the addresses could not be resolved. return; } echo $eindhoven->distanceTo($maarheeze)->asKilometers(); // e.g. 18.7
Caching
When geocode.cache.enabled is true, the bound service is wrapped in a CachingGeocode decorator. Every resolved address is stored in the cache table (keyed by the address string) and subsequent lookups of the same address are served from the database without calling the API. Addresses that cannot be resolved are not cached. Caching is transparent — consumers keep using the same Geocode contract.
License
MIT