pythongeolocation

How to get County Name from reverse GeoLocation look up?


I'm using python and the library from geopy.geocoders import Nominatim and I'm parsing through some Lat/Long coordinates and I want to get the county of the coordinates.

This is what I'm doing:

def getCounty(data):
    try:
        #print(data["geo"]["coordinates"])   # Getting Lat/Long coordinates
        geo_data = data["geo"]["coordinates"]
        geo_detail = geolocator.reverse(geo_data)

    except TypeError,e:
        geo_data = "null"
        geo_detail = "N/A"

    ctr = 0
    i = 0
    j = 0
    if(geo_detail != "N/A"):
        while(geo_detail[i]!= ',' and ctr == 4):
            j=j+1
            if(ctr == 3):
                i=j+1
            if(geo_detail[j] == ','):
                ctr = ctr+1
        county = geo_detail
    else:
        county = "No Location Provided"


    return county[i:j]

This for some reason returns ()

when I do: return county, It does return all the information from those coordinates.

It seems like I'm not able to get the substring of the variable county

How can I get the county attribute or what are other ways I could get the county?


Solution

  • Split that output string on the comma, and get the 4th index (the county):

    return geo_detail.address.split(",")[3] # Milwaukee County