pythonopenstreetmapgeocodinggeopy

get country from Nominatim GeoPy response


When using NOminatim with GeoPy to encode given address strings, how does one get the country information?

Is there any structured way to get the country name in the output? One way is to take the string after the last "," to get the country, but doesnt seem like a robust way to do so.

from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent='myapplication')
x = 'PA - Cranberry Township'
location = geolocator.geocode(x, exactly_one=True,language="english", namedetails=True)
# how to get country name from response
location.raw


{'place_id': 259010359,
 'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright',
 'osm_type': 'relation',
 'osm_id': 4131949,
 'boundingbox': ['40.673669', '40.7453357', '-80.1525583', '-80.0559393'],
 'lat': '40.7099343',
 'lon': '-80.1060506',
 'display_name': 'Cranberry Township, Butler County, Pennsylvania, 16066, United States',
 'class': 'boundary',
 'type': 'administrative',
 'importance': 0.6463910141518243,
 'icon': 'https://nominatim.openstreetmap.org/ui/mapicons//poi_boundary_administrative.p.20.png',
 'namedetails': {'name': 'Cranberry Township',
  'name:en': 'Cranberry Township',
  'official_name': 'Cranberry Township'}}

Solution

  • Here you go:

    from geopy.geocoders import Nominatim
    geolocator = Nominatim(user_agent='myapplication')
    x = 'PA - Cranberry Township'
    location = geolocator.geocode(x, exactly_one=True, language="en", namedetails=True, addressdetails=True)
    print(location.raw)
    print(f"""Country Name: {location.raw['address']['country']}""")
    

    Output:

    {
       "place_id":258908396,
       "licence":"Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright",
       "osm_type":"relation",
       "osm_id":4131949,
       "boundingbox":[
          "40.673669",
          "40.7453357",
          "-80.1525583",
          "-80.0559393"
       ],
       "lat":"40.7099343",
       "lon":"-80.1060506",
       "display_name":"Cranberry Township, Butler County, Pennsylvania, 16066, United States",
       "class":"boundary",
       "type":"administrative",
       "importance":0.6463910141518243,
       "icon":"https://nominatim.openstreetmap.org/ui/mapicons//poi_boundary_administrative.p.20.png",
       "address":{
          "town":"Cranberry Township",
          "county":"Butler County",
          "state":"Pennsylvania",
          "postcode":"16066",
          "country":"United States",
          "country_code":"us"
       },
       "namedetails":{
          "name":"Cranberry Township",
          "name:en":"Cranberry Township",
          "official_name":"Cranberry Township"
       }
    }
    Country Name: United States