Skip to content
Related Articles

Related Articles

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.

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# import module
from geopy.geocoders import Nominatim

chevron_right


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

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

data = location.raw
print(data)

chevron_right


Output:

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

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Full implementation:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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])

chevron_right


Output:

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :