1

I wish to get the country name given a latitude and longitude But, wish to avoid API call.

I tried reverse_geocoder, which seems to be slow and erroneous for few cases. Example below:

import reverse_geocoder as rg
coordinates = (34.024375,-119)
rg.search(coordinates)

Any way to get country name given lat, lng?

user13744439
  • 142
  • 1
  • 12

1 Answers1

0

You can use the library GeoPy Documentation link but it requires online interaction:

from geopy.geocoders import Nominatim

geolocator = Nominatim(user_agent="foo_bar")
coordinates = (34.024375, -119)
location = geolocator.reverse(coordinates)
country = location.address.split(',')[-1]

print(country)

Output of this code prints the country name for the given coordinates (lat/long), in this case United States

Version 2:

This code uses reverse_geocoder as you did:

from multiprocessing import freeze_support
import reverse_geocoder as rg

if __name__ == '__main__':
    freeze_support()
    coordinates = (34.024375, -119)
    location = rg.search(coordinates)
    country = location[0]['cc']

    print(country)

This prints the two-letter-code of the country, here US. You need the freeze_support() because otherwise Python wants to start a new process without the current one finished.

Gandhi
  • 346
  • 2
  • 9