Search code examples
pythonrgeolocation

how to map latitude/longitude to a specific US county?


I have a dataframe containing U.S. latitude and longitude coordinates.

I would like to create a variable that shows the respective U.S. county that includes these coordinates.

How can I do that in R/Python?

Thanks!


Solution

  • You could use geopy.

    Example from the documentation using Nominatim (Open Street Map):

    >>> from geopy.geocoders import Nominatim
    >>> geolocator = Nominatim(user_agent="http")
    >>> location = geolocator.reverse("52.509669, 13.376294")
    >>> print(location.address)
    Potsdamer Platz, Mitte, Berlin, 10117, Deutschland, European Union
    >>> print((location.latitude, location.longitude))
    (52.5094982, 13.3765983)
    >>> print(location.raw)
    {'place_id': '654513', 'osm_type': 'node', ...}
    

    The raw output has a dict key country, if one can be found.