Library resources | |
---|---|
PyPI | https://pypi.org/project/geopy/ |
Github | https://github.com/geopy/geopy |
Documentation | https://github.com/geopy/geopy |
27 Sep 2022
Getting started
pip3 install geopy
Used in Twittee Twittee
Usage
Here is a function using geopy that takes a location as input and returns the ISO country code of the location:
from geopy.geocoders import Nominatim
def get_country_code(location):
geolocator = Nominatim(user_agent="my-application")
try:
location = geolocator.geocode(location)
return location.raw['address']['country_code']
except:
return None
Not working with all locations - [address]
is missing in .raw
.
Workaround: combine geopy with pycountry Python library: pycountry to get latitude and longitude of a location and then use the latitude and longitude to get the ISO country code.
Also not working well.
At least, this function works - getting country name from location:
from geopy.geocoders import Nominatim
def country_name_by_location(location):
try:
geolocator = Nominatim(user_agent='myapplication')
location = geolocator.geocode(location)
loc_data = (location.raw["display_name"])
infos = loc_data.split(",")
final_val = infos[-1]
print(f"{final_val=}")
return final_val
except:
return None
TODO - get country code from country name.
Set of country names to test (returned from above function):
{ None,
' Algérie / ⵍⵣⵣⴰⵢⴻⵔ / الجزائر',
' Australia',
' België / Belgique / Belgien',
' Bermuda',
' Brasil',
' Canada',
' Chile',
' Danmark',
' Deutschland',
' Eesti',
' España',
' France',
' India',
' Italia',
' Kenya',
' Lietuva',
' Malta',
' Mauritius / Maurice',
' Nederland',
' Nigeria',
' Panamá',
' Philippines',
' Polska',
' Portugal',
' România',
' Schweiz/Suisse/Svizzera/Svizra',
' South Africa',
' Suomi / Finland',
' Sverige',
' Sénégal',
' Türkiye',
' United Kingdom',
' United States',
' Éire / Ireland',
' Česko',
' Россия',
' Србија',
' Україна',
' ישראל',
' الإمارات العربية المتحدة',
' السعودية',
' پاکستان',
' 中国',
' 日本',
' 臺灣',
'Lëtzebuerg',
'Singapore',
'United Kingdom'}
# 49 countries in set.