Search code examples
pythonpandasgeolocationgeospatialgeo

How to filter country from latitude and longitude?


I have a CSV of 2 Million row. There only two columns Latitude and longitude. I want to filter a country. For example, I want to filter only india's lat and long.


Solution

  • There are two ways to find a country from lat longs i.e. Online and Offline. I'll explain both below:

    Online

    You need to install a package called geopy

    pip install geopy
    

    Following code will let you reverse geocode the latitude and longitude using OpenStreetMap geocoding web service

    from geopy.geocoders import Nominatim
    geolocator = Nominatim(user_agent="test_app")  # enter a name for your app
    location = geolocator.reverse("27.1751, 78.0421")
    print(location.raw['address']['country'])
    

    However, it is not reliable.

    Offline

    A better option is to use offline geocoding using reverse-geocode

    pip install reverse-geocode
    

    Here's the sample code

    import reverse_geocode
    coords = (27.1751, 78.0421), (28.5245, 77.1855)
    reverse_geocode.search(coords)