When building real estate, logistics, or delivery apps, you often need to convert a physical address (street, city, postal code, country) into geographical coordinates (latitude and longitude). In this tutorial, I will show you how to integrate GeocoderLaravel with Google Maps API to achieve this in Laravel.
Why Use GeocoderLaravel?
GeocoderLaravel is a Laravel wrapper around the popular Geocoder PHP package. It makes working with geocoding services much easier inside Laravel projects.
Example Input: 16-18, Argyle Street, Camden, London, WC1H 8EG, United Kingdom
Example Output: [51.5291450, -0.1239401]
To achieve this, we’ll use Google Maps Geocoding API. Keep in mind that Google Maps API is not free. They provide limited free usage, but you must check pricing and monitor your API calls to avoid unexpected costs.
Step 1: Install GeocoderLaravel Package
composer require toin0u/geocoder-laravel
php artisan vendor:publish --provider="Geocoder\\Laravel\\Providers\\GeocoderService"
After publishing, you’ll get a configuration file at config/geocoder.php
.
Step 2: Add Google Maps API Key
First, generate your API key from the Google Cloud Console . It will look like this:
GOOGLE_MAPS_API_KEY=AIzaSyAWRsRGOFbTXRlLHDOSudkerLjUtBfElUt
Then, configure config/geocoder.php
to use Google Maps:
return [
// Other configs ...
'providers' => [
Chain::class => [
GoogleMaps::class => [
env('GOOGLE_MAPS_LOCALE', 'us'),
env('GOOGLE_MAPS_API_KEY'), // Google API key here
],
GeoPlugin::class => [],
],
],
];
Finally, add your API key to the .env
file:
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:wgvwuEojBNlCrmg7Pmn3x...
APP_DEBUG=true
# Google Maps API Key
GOOGLE_MAPS_API_KEY=AIzaSyAWRsRGOFbTXRlLHDOSudkerLjUtBfElUt
⚠️ Important Security Note: Never expose your API key publicly. Restrict it in the Google Cloud Console (e.g., by domain or IP). If leaked, malicious users could abuse it and charge your billing account.
Step 3: Call Geocoder for Coordinates
Here’s a simple example to fetch latitude and longitude:
<?php
$address = "16-18, Argyle Street, Camden, London, WC1H 8EG, United Kingdom";
$result = app('geocoder')->geocode($address)->get();
if ($result->count() > 0) {
$coordinates = $result[0]->getCoordinates();
$lat = $coordinates->getLatitude();
$long = $coordinates->getLongitude();
echo "Latitude: {$lat}, Longitude: {$long}";
} else {
echo "No coordinates found for this address.";
}
You can call this in a Controller, Service Class, or even a Queued Job. Using a Job is recommended if you expect delays due to API response times.
Conclusion
With just a few steps, you can easily integrate Google Maps geocoding into your Laravel project using GeocoderLaravel. This allows you to transform user-entered addresses into accurate latitude/longitude values, useful for maps, delivery tracking, or property search features.