I am facing a weird situation when I sent request to the google geocode JSON API endpoint with the following function inside a Laravel controller
https://maps.googleapis.com/maps/api/geocode/json?address=New%20California,%20Ohio,%20United%20States&key=<key>
<?php
// ... class
protected function geocodeCity($city) {
$client = new Client();
$apiKey = env('GOOGLE_MAPS_API_KEY');
$response = $client->get("https://maps.googleapis.com/maps/api/geocode/json", [
'query' => [
'address' => $city,
'key' => $apiKey
],
'headers' => [
'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36'
]
]);
$data = json_decode($response->getBody(), true);
if ($data['status'] === 'OK') {
$location = $data['results'][0]['geometry']['location'];
$addressComponents = $data['results'][0]['address_components'];
$postalCode = null;
foreach ($addressComponents as $component) {
if (in_array('postal_code', $component['types'])) {
$postalCode = $component['long_name'];
break;
}
}
return [
'latitude' => $location['lat'],
'longitude' => $location['lng'],
'postal_code' => $postalCode
];
}
return null;
}
It return only 4 key of address_components
in the response
but when I sent https://maps.googleapis.com/maps/api/geocode/json?address=New%20California,%20Ohio,%20United%20States&key=<key>
it return total 6 key including postal_code
Initially I thought that it’s happening due to User-Agent so I added User-Agent but still same, I can’t figure it out why this problem occurring.
I tried using Client URL Library ( cURL ) when I failed using GuzzleHttp but it’s still same to be noted that the project laravel framework version "laravel/framework": "^8.75"
and guzzle version "guzzlehttp/guzzle": "^7.8",
I tried to change the version but still same. I wanted to see the 6 key which have postal_code type from there I can get "long_name": "43064",
key value.