Open In App

Get Zip Code with given location using GeoPy in Python

In this article, we are going to write a python script to get the Zip code by using location 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:

Step-by-step implementation:



Step #1: Import module.




# import module
from geopy.geocoders import Nominatim

Step #2: Make a Nominatim object and initialize Nominatim API  with the geoapiExercises parameter.




# initialize Nominatim API 
geolocator = Nominatim(user_agent="geoapiExercises")

Step #3:  Now get a complete address with geocode().




place = "Boring road patna"
location = geolocator.geocode(place)
print(location)

Output:

Boring Road, Digha, Patna, Patna Rural, Patna, Bihar, 800001, India

Step #4: Now get the information from the given list and parsed into a dictionary with raw function().




data = location.raw
print(data)

Output:

Step #5: Now traverse the ZIP Code from a given dictionary.




loc_data = data['display_name'].split()
print("Full Location")
print(loc_data)
print("Zip code : ",loc_data[-2])

Output:

Full implementation:




# import module
from geopy.geocoders import Nominatim
  
# initialize Nominatim API 
geolocator = Nominatim(user_agent="geoapiExercises")
  
# place input by geek
place = "Boring road patna"
location = geolocator.geocode(place)
  
# traverse the data
data = location.raw
loc_data = data['display_name'].split()
print("Full Location")
print(loc_data)
print("Zip code : ",loc_data[-2])

Output:


Article Tags :