Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 316
Eyal S. Avatar asked Oct 20 '25 04:10

Eyal S.


1 Answers

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
like image 78
chickity china chinese chicken Avatar answered Oct 21 '25 18:10

chickity china chinese chicken



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!