Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Get Zip Code with given location using GeoPy in Python

  • Last Updated : 25 Oct, 2020

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.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

pip install geopy

Approach:



  • Import the Geopy module
  • Initialize Nominatim API to get location from the input string.
  • Get location with geolocator.geocode() function.
  • Now extract the Zip data from the location instance.

Step-by-step implementation:

Step #1: Import module.

Python3




# import module
from geopy.geocoders import Nominatim

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

Python3




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

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

Python3




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().

Python3




data = location.raw
print(data)

Output:

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

Python3




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

Output:

Full implementation:

Python3




# 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:




My Personal Notes arrow_drop_up
Recommended Articles
Page :