Kristi Jorgji
Kristi Jorgji

Reputation: 1739

How to get the country place using the countryCodeIso2 from google geocoding api?

I am using

https://developers.google.com/maps/documentation/geocoding/requests-geocoding

https://maps.googleapis.com/maps/api/geocode/json

My use case is this: I have country codes in iso 2 (2 chars) format and want to get the country place from the geocoding api.

I have JP for example. How to call this api and get only a single response back of type country.

I am trying right now:

 $locale = 'en';
 $response = $this->httpClient->get(
            'https://maps.googleapis.com/maps/api/geocode/json',
            [
                RequestOptions::HTTP_ERRORS => false,
                RequestOptions::QUERY => [
                    'key' => 'apikey',
                    'address' => urlencode('JP'),
                    'components' => 'country',
                    'language' => (string)$locale,
                ]
            ]
        );

and get no results as expected as the country code is not an address..

{
   "results" : [],
   "status" : "ZERO_RESULTS"
}

I get 0 results like this. I am not seeing in the documentation any countrycode or similar field but just the address.

I am open to use also the google maps service not only limited to the geocoding so any suggestion is welcome. THanks

Upvotes: 1

Views: 101

Answers (1)

miguev
miguev

Reputation: 4875

It looks like you may be sending a malformed request to the Geocoding API, such as

https://maps.googleapis.com/maps/api/geocode/json?components=country&address=JP

which indeed returns ZERO_RESULTS. The correct request would be

https://maps.googleapis.com/maps/api/geocode/json?components=country:JP

Perhaps this will work:

                RequestOptions::QUERY => [
                    'key' => 'apikey',
                    'components' => 'country:JP',
                    'language' => (string)$locale,
                ]

Note that the address parameter is not necessary if the components parameter is correctly formatted.

If you are wondering why ZERO_RESULTS are returned for address=JP, the short answer is that, in a global context, JP all by itself is too ambiguous.

To get a more concrete idea, I would suggest you try going to maps.googlemaps.com and type just JP on the search box and then, and this is the important bit, just hit the Enter key (and not click/tap on any suggestions). In my case, the result is a list of businesses such as "J.p. Motorcycles" or "J & P Fine Art", depending on what part of the world is visible on Google Maps at the moment of hitting the Enter key.

Upvotes: 0

Related Questions