Sergey Romanov
Sergey Romanov

Reputation: 3080

How to get list of states in a country through Google map API?

Is it at all possible. I had spent 5 hours researching and did not find a solution.

Does anyone knows anything?

Upvotes: 3

Views: 10903

Answers (4)

Dula
Dula

Reputation: 1412

As mentioned in other answers, Google Map API does not support this function. But I found 2 ways to get around this issue.

Solution 1 : Use Country State City API

This is a third party API that returns the list of states for the passed country.

Link to Country State City API website Link to GitHub Repo

You need to submit a request through the website to acquire an API key. Following is the code that I used to fetch states for a country.

$countryCode = 'US'; // AU, US, IN, GB
$headers = [
        'X-CSCAPI-KEY' => 'API_KEY',
        'Content-Type' => 'application/json',
        'Accept' => 'application/json'
    ];

$options = [
        RequestOptions::HEADERS => $headers,
    ];

$endPoint = 'https://api.countrystatecity.in/v1/countries/' . $countryCode . '/states';

$response = $this->guzzleClient->get($endPoint, $options);

$content = $response->getBody()->getContents();
return json_decode($content, true);

Even though, this API is simple and awesome there is the ISSUE OF TRUST as the API provider is not a registered company. (for my understanding)

Solution 2:

Download the iso-3166-2.json JSON file from GitHub and read the file to get the list of states for the country.

Link to the GitHub Repo

Following is the code for my implementation.

$countryCode = 'US'; // AU, US, IN, GB
$jsonSrc = file_get_contents($jsonPath);
$countryStates = json_decode($jsonSrc, true);

$countryData = $countryStates[$countryCode];

if ($countryData) {
        
        $stateList = $countryData['divisions'];

        foreach ($stateList as $key => $value) {
            $states[] = $value;
        }
    }

I think this is the safest option as the list is managed locally by you. The down side is that you have to update the list, if there any changes in the world.

Upvotes: 0

Sud
Sud

Reputation: 303

Pls check out the ISO-3166-2. It is an ISO standard based on country. You need not rely on Google Maps or any other webservice. It is available as a pure JSON file.

Upvotes: 2

david strachan
david strachan

Reputation: 7228

The Geonames geographical database is available for download free of charge under a creative commons attribution license has various data sets that may help. The one which suits your requirements is admin2Codes.txt

Upvotes: 2

geocodezip
geocodezip

Reputation: 161324

That is not part of the Google Maps API v3. You can use the Natural Earth Data set in Fusion Tables to get that information. Here is an example displaying the provinces of Canada on a Google Map using FusionTablesLayer.

Upvotes: 4

Related Questions