
When working with addresses in web applications, retrieving detailed address components, such as city, state, country, and zip code, can be useful for enhancing user experience or data processing.
Step 1. Set Up Google Maps API Key:
- Go to Google Cloud Console
- Create a project (If not already created)
- Enable the Geocoding API under APIs & Services.
- Generate an API key.
Step 2. Function to Fetch Geocode Data:
if (!function_exists('getGeocodeData')) {
/**
* Get geocode data for an address using Google Maps API.
*
* @param string $address
* @return array|null
*/
function getGeocodeData($address = '')
{
$api_key = config('app.google_map_api_key');
if (!$address) {
return null;
}
$url = "https://maps.googleapis.com/maps/api/geocode/json";
$response = Http::get($url, [
'address' => $address,
'key' => $api_key,
]);
if ($response->ok()) {
$data = $response->json();
if (!empty($data['results'])) {
$result = $data['results'][0];
return [
'formatted_address' => $result['formatted_address'],
'city' => getAddressComponent($result['address_components'], 'locality'),
'state' => getAddressComponent($result['address_components'], 'administrative_area_level_1'),
'country' => getAddressComponent($result['address_components'], 'country'),
'country_code' => getAddressComponent($result['address_components'], 'country', 'short_name'),
'zip' => getAddressComponent($result['address_components'], 'postal_code'),
'latitude' => $result['geometry']['location']['lat'],
'longitude' => $result['geometry']['location']['lng'],
];
}
}
return null;
}
}
Step 3. Helper function for Address Components :
The getAddressComponent function helps extract specific components from the address_components array returned by the Google Maps API.
if (!function_exists('getAddressComponent')) {
/**
* Extract a specific component from address components.
*
* @param array $components
* @param string $type
* @param string $nameType
* @return string|null
*/
function getAddressComponent($components, $type, $nameType = 'long_name')
{
foreach ($components as $component) {
if (in_array($type, $component['types'])) {
return $component[$nameType] ?? null;
}
}
return null;
}
}
Step 4. Usage Example:
$address = "1600 Amphitheatre Parkway, Mountain View, CA";
$geocodeData = getGeocodeData($address);
if ($geocodeData) {
echo "Formatted Address: " . $geocodeData['formatted_address'] . "\n";
echo "City: " . $geocodeData['city'] . "\n";
echo "State: " . $geocodeData['state'] . "\n";
echo "Country: " . $geocodeData['country'] . "\n";
echo "Country Code: " . $geocodeData['country_code'] . "\n";
echo "Zip Code: " . $geocodeData['zip'] . "\n";
echo "Latitude: " . $geocodeData['latitude'] . "\n";
echo "Longitude: " . $geocodeData['longitude'] . "\n";
} else {
echo "No geocode data found for the given address.";
}
* Please Don't Spam Here. All the Comments are Reviewed by Admin.