How to Get Geolocation in Python

Published on Aug. 22, 2023, 12:15 p.m.

To get geolocation in Python, you can use the Geopy library, which provides access to several popular geocoding web services. Here’s how you can use Geopy to get the latitude and longitude coordinates of an address:

  1. Install Geopy using pip:
pip install geopy
  1. Import the necessary modules:
from geopy.geocoders import Nominatim
  1. Initialize the Nominatim geocoder object:
geolocator = Nominatim(user_agent="my_app_name")
  1. Use the geocode() method of the geolocator object and pass it the address as a string:
location = geolocator.geocode("1600 Amphitheatre Parkway, Mountain View, CA")
  1. Access the latitude and longitude coordinates of the location object:
print((location.latitude, location.longitude))

This will output the following:

(37.4219999, -122.0840575)

In this example, we used the geocode() method of the Nominatim geocoder object to obtain the latitude and longitude coordinates of the Google headquarters in Mountain View, California. You can replace this address with any other address that you’re interested in.

Tags:

related content