Eyal S.
Eyal S.

Reputation: 1161

Find the county for a city, state

I have a city + state information and I'm trying to find the county. I tried a few things. The closest I got is using geopy. Here is an example:

from geopy.geocoders import Nominatim
geolocator = Nominatim()
loc = geolocator.geocode('Chicago Illinois')
print(loc.address)
# u'Chicago, Cook County, Illinois, United States of America'
loc = geolocator.geocode('San Francisco California')
print(loc.address) 
# u'SF, California, United States of America'

The problem is that it is unclear if the county is part of the output and if it is how to extract it using code (the string format seems to change).

What is the best way to get County information for a city + state?

Upvotes: 4

Views: 27076

Answers (4)

Kavikayal
Kavikayal

Reputation: 143

Please extract the last word which is country name using the below code.

from geopy.geocoders import Nominatim

geolocator = Nominatim(timeout=3)

location = geolocator.geocode('Chicago Illinois',language='en')

loc_dict = location.raw

print(loc_dict['display_name'])

print (loc_dict['display_name'].rsplit(',' , 1)[1])


location = geolocator.geocode('San Francisco California')

loc_dict = location.raw

print(loc_dict['display_name'])

print (loc_dict['display_name'].rsplit(',' , 1)[1])

Upvotes: 1

Here is a geocoder solution that will help you get the county data. If you don't already have it installed, you can pip install geocoder.

import geocoder

results = geocoder.google("Chicago, IL")

print(results.current_result.county)

enter image description here

Upvotes: 3

That's one weakness as geopy does not guarantee county in its response. If you're open to other APIs, the U.S. Small Business Administration has an U.S. City & County Web Data API with an "All data for a specific City" endpoint, that has counties for cities that are ambiguously both cities and counties like City and County of San Francisco.

The API has xml or json response formats. The only change needed for your examples is using state abbreviations:

import requests
import json

locations = ['Chicago, IL', 'San Francisco, CA']

city_data_url = 'http://api.sba.gov/geodata/primary_links_for_city_of/%s/%s.json'

for l in locations:
    split_name = l.split(', ')
    response = requests.get(city_data_url % tuple(split_name))

    resp_json = json.loads(response.text)
    print resp_json[0]['full_county_name']

Output:

Cook County
San Francisco County

Upvotes: 3

FieryCat
FieryCat

Reputation: 1889

It can be used Google API as well within a list "address_components" [Country -> State -> County -> ...]:

request(
    'http://maps.googleapis.com/maps/api/geocode/json', 'GET', {
        'address': 'Chicago Illinois'
        'language': 'en',
        'sensor': 'true'
    }
)

In case, from the first list was taken too many variations, you have to define the proper long/lat :

request(
    'http://maps.googleapis.com/maps/api/geocode/json', 'GET', {
        'latlng': "${Latitude},${Longitude}",
        'language': 'en',
        'sensor': 'true'
    }
)

Another sample, Yahoo API:

request('https://query.yahooapis.com/v1/public/yql', 'GET', {
    'q': "select * from geo.places.parent where child_woeid in (select woeid from geo.places where text='Chicago, Illinois')",
    'market': 'en-gb',
    'format': 'json',
    'env': 'store%3A%2F%2Fdatatables.org%2Falltableswithkeys',
    'callback': ''
})

Assume, directly the same way can be used in any GEO API.

Upvotes: 1

Related Questions