3

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?

roganjosh
  • 12,594
  • 4
  • 29
  • 46
Eyal S.
  • 1,141
  • 4
  • 17
  • 29
  • So "County" for the first quest should be "Cook County"? The second, I have no idea. OSM data is haphazard, I'm not sure you can do this. `print loc.raw` will show you what's available. – roganjosh May 26 '17 at 19:28
  • You could try pygeocoder. – SH7890 May 26 '17 at 19:47

4 Answers4

2

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
  • 1
    This API appears to be defunct, I get a 404 from the supposed portal: https://www.sba.gov/about-sba/sba-performance/sba-data-store/web-service-api/us-city-and-county-web-data-api – ericksonla Oct 21 '18 at 22:16
2

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

1

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.

FieryCat
  • 1,875
  • 18
  • 28
  • 2
    "Country" and "County" are different. It's either a typo in the question or you have misunderstood. – roganjosh May 26 '17 at 19:30
  • @roganjosh, sorry, inattentiveness, but it's applicable for County as a part of "address_components" https://developers.google.com/maps/documentation/geocoding/intro?hl=en – FieryCat May 26 '17 at 19:33
  • Ok, that's a different service. If this can answer the "county" question for both examples then I think it's a decent answer as long as you include any API restrictions (number of requests per unit of time). I'm not sure that OSM carries this data reliably. – roganjosh May 26 '17 at 19:35
  • For geopy it's also there: http://nominatim.openstreetmap.org/search/Chicago/Illinois?format=xml&polygon=1&addressdetails=1 `Cook County` – FieryCat May 26 '17 at 19:39
  • And for the second example? The OP already shows "Cook County" in the question. – roganjosh May 26 '17 at 19:41
  • Yeah, second request wasn't a good case... mostly it was used to clarify the proper value from the first list. – FieryCat May 26 '17 at 19:44
  • Which is why I would upvote your answer if you give an alternative with the associated API caps :) I had a hard time parsing OSM data for this kind of thing, it's very unreliable for complete data unfortunately. You linked to Google. – roganjosh May 26 '17 at 19:48
  • https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.places.parent%20where%20child_woeid%20in%20(select%20woeid%20from%20geo.places%20where%20text=%27Chicago,%20Illinois%27)&market=en-gb&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback= – FieryCat May 26 '17 at 20:03
1

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])
Kavikayal
  • 143
  • 4
  • 14