Open In App

Get Zip Code with given location using GeoPy in Python

Improve
Improve
Like Article
Like
Save
Share
Report

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:

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



Last Updated : 25 Oct, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads