Get GPS Coordinates in Python

Learn how to get latitude and longitude in Python from an address using geopy, and how to get approximate current location from an IP address.

Published

Updated

Read time 6 min read

Reviewed byDeepak Prasad

Get GPS Coordinates in Python

If you want latitude and longitude from a street address or place name, Python can do that with geocoding—in this guide, using geopy and Nominatim. If you want a quick, coarse idea of where a request originated, you can call an IP geolocation API over HTTPS; that is handy, but it is not the same as reading GPS from a phone or browser. For HTTP calls to external APIs, see Python requests; for unique IDs tied to location records, see Python UUID examples.

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.

The geopy snippets below were run successfully in a disposable virtual environment (python3 -m venv /tmp/geopytest followed by that environment’s pip install geopy). If your system blocks system-wide installs (PEP 668), use a venv the same way before pip install geopy. To install geopy from its Git repository instead of PyPI, see install a Python package from GitHub.


Can Python get GPS coordinates?

You will not get a phone-style GPS fix from a plain Python script sitting on a server. What you can do from typical scripts is:

  • Call geocoding APIs (here via geopy) to resolve text addresses to coordinates.
  • Call IP geolocation HTTP APIs (for example ipinfo.io) to get rough coordinates associated with your public IP—not the same as a GPS fix.
  • In apps, you can combine Python on a server with client-side browser navigator.geolocation or mobile SDKs when you need real GPS permission flows (outside the scope of these short server-style snippets).
Need Practical approach
Coordinates from an address Geocoding with geopy (Nominatim or another backend)
Address from coordinates Reverse geocoding with the same tooling
Approximate “where am I” without a device API IP geolocation over HTTPS
True GPS accuracy Device/browser location APIs or GPS hardware + vendor stacks
Random latitude/longitude random module or test fixtures—not navigation

Get latitude and longitude from an address using geopy

Install geopy (third-party). urllib is not installed this way—it is part of the standard library for URL work and ships with Python already.

text
pip install geopy

Nominatim powers OpenStreetMap search. The public instance has a usage policy: send modest request rates, cache results, always identify your traffic with a real user_agent, and do not bulk-scrape the service. For production, run your own Nominatim instance or use a commercial geocoder; the geopy documentation reminds you that each geocoder has its own terms and limits.

python
from geopy.geocoders import Nominatim

def get_coordinates(address):
    geolocator = Nominatim(user_agent="replace_with_your_app_or_domain")
    location = geolocator.geocode(address, timeout=10)
    if location is None:
        raise ValueError(f"No geocoding match for {address!r}")
    return location.latitude, location.longitude

def print_coordinates(address):
    lat, lon = get_coordinates(address)
    print("Latitude:", lat)
    print("Longitude:", lon)

print_coordinates("1600 Amphitheatre Parkway, Mountain View, CA")
text
Latitude: 37.4224858
Longitude: -122.0855846

That transcript came from a live Nominatim lookup while revising this page; coordinates can shift slightly as the database changes. The snippet stays {run=false} because it needs network access and must respect provider rate limits.


Get approximate current location using IP address

The following pattern calls ipinfo’s JSON endpoint over HTTPS and reads the loc field ("latitude,longitude"). That reflects IP geolocation: useful for coarse “which city or region” hints, not GPS accuracy and not guaranteed to be where you are standing. IPinfo documents fields such as city, region, country, coordinates, and timezone for IP data (product overview).

python
import json
from urllib.request import urlopen

with urlopen("https://ipinfo.io/json", timeout=10) as resp:
    data = json.load(resp)

lat, lon = data["loc"].split(",")
print("Approximate IP-based coordinates:", lat, lon)
text
Approximate IP-based coordinates: 60.2052 24.6522

Your printed numbers will match your network’s exit point, not the sample line above. Do not run pip install urllib; it is the wrong lesson and often drags in unrelated packages such as urllib3. Standard-library urllib.request is enough for this style of call.


GPS location vs IP location vs geocoding

  • Geocoding (forward): structured text → coordinates. Accuracy depends on the provider and how well the address parses.
  • Reverse geocoding: coordinates → description or postal address.
  • IP “location”: maps an internet route to a coarse area. VPNs, mobile carriers, and corporate NAT can place you hundreds of kilometers from the returned point.
  • GPS / GNSS: satellite receiver or fused mobile location; requires device permissions and different APIs than a plain server script.
  • Random coordinates: synthetic data for games or tests—unrelated to resolving a real place.

Keeping these meanings separate prevents bugs when stakeholders assume IP or geocoding results are survey-grade GPS.


Reverse geocoding: coordinates to address

Use reverse on the same geocoder object. Respect the same Nominatim usage limits as forward geocoding.

python
from geopy.geocoders import Nominatim

geolocator = Nominatim(user_agent="replace_with_your_app_or_domain")
location = geolocator.reverse((37.4225, -122.0856), timeout=10)
print(location.address)
text
Google Building 41, 1600, Amphitheatre Parkway, Mountain View, Santa Clara County, California, 94043, United States

Handle None when the service has no match. String length and wording can vary by data version.


Common mistakes when getting coordinates in Python

  • Running pip install urlliburllib is stdlib; mixing it up with urllib3 confuses beginners.
  • Treating IP geolocation JSON as GPS truth for navigation or compliance.
  • Hitting Nominatim without a descriptive user_agent, or hammering the public endpoint in a tight loop—risk of blocking per the OSM policy.
  • Omitting timeout= on network geocoders, leaving scripts hanging on slow responses.
  • Assuming geocode always finds a hit; check for None before reading .latitude.
  • Using pandas when it adds no value—keep examples minimal unless you are batching rows.
  • Passing coordinates in the wrong order (lon, lat vs lat, lon) when calling mapping tools—reverse geocoding here expects (latitude, longitude).

Python GPS coordinates quick reference table

Task Python building blocks Accuracy / caveat
Address → lat/lon geopy + Nominatim (or other geocoder) Depends on address quality and provider
Lat/lon → label geolocator.reverse(...) Same limits as forward geocoding
Public IP → coarse lat/lon urllib.request + JSON API Network exit, not device GPS
Device GPS Browser / mobile SDKs, not shown here User permission, hardware dependent
Random test points random.uniform for lat/lon ranges Synthetic only

Summary

When you have an address or place name and need coordinates, reach for geopy with Nominatim (or another geocoder you control). When you already have a point and need a readable label, use reverse geocoding the same way. When you only need a rough hint from the client’s IP, HTTPS JSON services such as ipinfo are fine—just be clear with yourself and your users that this is not GPS. Skip pip install urllib; use the standard library for simple fetches, install geopy only when you need geocoding helpers, and read each provider’s policy before you put heavy traffic against shared endpoints.


References


Frequently Asked Questions

1. Does reading ipinfo.io/json give my phone GPS location?

No—it returns approximate coordinates tied to your public IP network exit, which can be far from your device and is unrelated to GPS chip or browser geolocation permission.

2. Why must I set a custom user_agent with Nominatim?

OpenStreetMap requires identifiable requests; geopy passes user_agent through to the service so operators can enforce the public usage policy and block anonymous bulk traffic.

3. Can I use urllib to install geocoding support?

urllib is in the standard library and is not installed with pip; install third-party helpers such as geopy with pip only when you need them.

4. What is the difference between geocoding and reverse geocoding?

Geocoding turns a place name or address into coordinates; reverse geocoding starts from coordinates and finds a human-readable address or place description.
Azka Iftikhar

Computer Scientist

Proficient in multiple programming languages, including C++, Golang, and Java, she brings a versatile skillset to tackle a wide array of challenges. Experienced Computer Scientist and Web Developer, …