Converting Addresses to Geocoordinates Using Python

Converting Addresses to Geocoordinates Using Python

Usage

The script provides a facility to the user to input an address or any location and retrieves the equivalent geocode—latitude and longitude—and displays it using the geopy library.


Summary

The script leverages the geopy library to get geographic coordinates in latitude and longitude from a location the user provides. It makes contact with the user for the location input and further contacts the nominatim geocoding service to retrieve and display the geocode.


from geopy.geocoders import Nominatim

geolocator = Nominatim(user_agent="geoapiExercises")

location = input("Enter the address or location: ")

geocode = geolocator.geocode(location)

if geocode:
    print(f"Address: {geocode.address}")
    print(f"Latitude: {geocode.latitude}")
    print(f"Longitude: {geocode.longitude}")
else:
    print("Geocode not found.")        



Procedure

  • Initialize Geocoder

The script starts by creating an instance of Nominatim geocoder, which is further used for geocoding the address or location provided by a user into geographic coordinates.

  • User Input

This script, at the outset, asks the user to enter the address or location from the command line or terminal and receives this input in a variable named location.

  • Get Geocode

It will then attempt to get the geocode for the location using the geocoder instance. The result is stored in the geocode variable, that will hold latitude, longitude, and the full address.

  • Output

If the geocode is successfully retrieved, the full address, latitude, and longitude of the location are printed.

In case the location is not found, it will print a message notifying the user that the geocode was not found.


Thanks For Reading

To view or add a comment, sign in

More articles by Ayush G.

Explore content categories