Get the city, state, and country names from latitude and longitude using Python
Last Updated :
31 May, 2022
In this article, we are going to write a python script to get the city, state, and country names by using latitude and longitude using the Geopy module.geopy makes it easy for Python developers to locate the coordinates of addresses, cities, countries, and landmarks across the world.
To install the Geopy module, run the following command in your terminal.
pip install geopy
Approach:
- Import the Geopy module
- Initialize Nominatim API to get location from the input string.
- Get location with geolocator.reverse() function.
- Now extract the data from the location instance
Let’s implement with step by step:
Step #1: Import the module.
Python3
from geopy.geocoders import Nominatim
|
Step #2: Make a Nominatim object and initialize Nominatim API with the geoapiExercises parameter.
Python
geolocator = Nominatim(user_agent = "geoapiExercises" )
|
Step #3: Now assign the latitude and longitude into a geolocator.reverse() method. A reverse() methods require the argument query, and also accept at least the argument exactly_one, which is True by default.
Python3
Latitude = "25.594095"
Longitude = "85.137566"
location = geolocator.reverse(Latitude + "," + Longitude)
print (location)
|
Output:
[Location(Rajendra Nagar, Patna, Patna Rural, Patna, Bihar, 800001, India, (25.594023552508407, 85.13756080147536, 0.0))]
Step #4: Now get the information from the given list and parsed into a dictionary with raw function().
Python3
address = location.raw[ 'address' ]
print (address)
|
Output:
{'suburb': 'Rajendra Nagar',
'city': 'Patna',
'country': 'Patna Rural',
'state_district': 'Patna',
'state': 'Bihar',
'postcode': '800001',
'country': 'India',
'country_code': 'in'}
Step #5: Now traverse the city, state, and country names.
Python3
city = address.get( 'city' , '')
state = address.get( 'state' , '')
country = address.get( 'country' , '')
code = address.get( 'country_code' )
zipcode = address.get( 'postcode' )
print ( 'City : ' ,city)
print ( 'State : ' ,state)
print ( 'Country : ' ,country)
print ( 'Zip Code : ' , zipcode)
|
Output:
City : Patna
State : Bihar
Country : India
Zip Code : 800001
Full implementation:
Python3
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent = "geoapiExercises" )
Latitude = "25.594095"
Longitude = "85.137566"
location = geolocator.reverse(Latitude + "," + Longitude)
address = location.raw[ 'address' ]
city = address.get( 'city' , '')
state = address.get( 'state' , '')
country = address.get( 'country' , '')
code = address.get( 'country_code' )
zipcode = address.get( 'postcode' )
print ( 'City : ' , city)
print ( 'State : ' , state)
print ( 'Country : ' , country)
print ( 'Zip Code : ' , zipcode)
|
Output:
City : Patna
State : Bihar
Country : India
Zip Code : 800001
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...