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.geolocationor 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.
pip install geopyNominatim 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.
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")Latitude: 37.4224858
Longitude: -122.0855846That 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).
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)Approximate IP-based coordinates: 60.2052 24.6522Your 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.
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)Google Building 41, 1600, Amphitheatre Parkway, Mountain View, Santa Clara County, California, 94043, United StatesHandle 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 urllib—urllibis stdlib; mixing it up withurllib3confuses 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
geocodealways finds a hit; check forNonebefore reading.latitude. - Using
pandaswhen it adds no value—keep examples minimal unless you are batching rows. - Passing coordinates in the wrong order (
lon, latvslat, 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
- urllib — URL handling modules (standard library)
- geopy documentation
- Nominatim usage policy
- ipinfo.io (IP geolocation product overview)

