For a website to ask for the visitor’s device location, use the browser’s JavaScript navigator.geolocation API. For Python, make an HTTPS request to a geolocation service such as Google’s: Python does not have access to the browser’s navigator object. These are different approaches with different inputs, permissions, and privacy requirements. Neither guarantees an exact location.
Choose the right geolocation approach
Start by identifying where the location information will come from. A browser page can ask the hosting device for a location estimate through the W3C Geolocation API. A Python program running on a server can instead send network observations to a hosted service, which returns its own estimate. Google’s Geolocation API is one such service; it is not the browser API under another name.
| Question | Browser JavaScript | Python with Google’s Geolocation API |
|---|---|---|
| Where does the estimate come from? | The hosting device and location sources available to it; the browser abstracts those sources from the page. | Network observations submitted in the request, such as Wi-Fi access points or cell towers. |
| Does the visitor grant permission? | The browser controls permission and prompts the user when needed. | The endpoint call itself does not use the browser permission prompt. You must have a legitimate basis to collect and submit the observations. |
| What does the code receive? | A position with coordinates and an accuracy value, among other position data. | A response containing a location with latitude and longitude and an accuracy radius. |
| What does the application need? | A browser that supports the API, a secure context, and permission when requested. | An API credential, enabled billing, and suitable network observations or the service’s IP-based option. |
In both cases, treat coordinates as estimates. The W3C specification says the API is agnostic about the underlying location source and does not guarantee that the result is the device’s actual location. Accuracy varies with the source and conditions; do not promise GPS-level precision based on the API alone.
Get the current position in JavaScript
Use feature detection, request a one-time position, and handle both success and failure. The browser’s normal permission flow should remain visible to the user; do not try to bypass it. Run the example from a secure context such as HTTPS in deployment. Browser behavior can vary by browser and environment.
#1 Best Overall
- 📱 Global Cloud Positioning – Works with both Google's Find Hub (Android Only,Not for GPS & ios)
- 📢 Loud Alert Sound – Built-in speaker with up to 85dB for quick locating
- 🔋 Far Superior Battery Life – Up to 2 years battery life on Android
- 💧 IP65 Waterproof – It provides protection against rainwaterand splashes
- 👮 Data Encryption – With the help of Google's technology, all location information is encrypted
const output = document.querySelector("#location-result");
function showError(error) {
const messages = {
1: "Location permission was denied.",
2: "The device could not determine a location.",
3: "The location request timed out."
};
output.textContent = messages[error.code] || "Could not get a location.";
}
if (!("geolocation" in navigator)) {
output.textContent = "This browser does not support geolocation.";
} else {
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude, accuracy } = position.coords;
output.textContent =
`Latitude: ${latitude}, longitude: ${longitude}, ` +
`estimated accuracy: ${Math.round(accuracy)} meters.`;
},
showError,
{
enableHighAccuracy: false,
timeout: 10000,
maximumAge: 60000
}
);
}
Pair it with an element in the page, for example <p id="location-result">Location not requested.</p>. Call getCurrentPosition(success, error, options) in response to a clear user action, such as pressing a “Use my location” button. That makes the purpose of the permission request understandable.
What the options mean
enableHighAccuracyis a request for a more accurate result where possible, not a guarantee that the device will use GPS or meet a particular precision.timeoutsets how long the page is willing to wait for a response before treating the request as timed out.maximumAgeallows a cached position no older than the specified age in milliseconds. Use0when you do not want an older cached result accepted; that still does not guarantee a fresh or more accurate fix.
Inspect position.coords.latitude, longitude, and accuracy together. The accuracy value is expressed in meters as an estimate of the uncertainty radius; it is not a promise that the true position lies within that radius in every case. Avoid displaying excessive decimal places as if they represented real-world certainty.
Watch position updates and stop the watch
Use watchPosition() when the page needs updates as the device’s reported position changes, rather than repeatedly firing one-shot requests. It returns an ID that you must pass to clearWatch() when updates are no longer needed.
if (!("geolocation" in navigator)) {
throw new Error("This browser does not support geolocation.");
}
const watchId = navigator.geolocation.watchPosition(
(position) => {
console.log({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
accuracyMeters: position.coords.accuracy
});
},
(error) => {
console.error("Location update failed:", error.message);
},
{ enableHighAccuracy: false, timeout: 10000, maximumAge: 5000 }
);
// Call this when tracking should stop, for example when the user taps Stop.
function stopWatching() {
navigator.geolocation.clearWatch(watchId);
}
Keep the watch active only while the feature needs it. Tell users when ongoing location updates are active, provide a visible way to stop them, and do not assume that a watch produces updates at a fixed interval.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Rank #2
- Premium GPS Tracker — The LandAirSea 54 GPS tracker provides accurate global location, real-time alerts, and geofencing. Easily attaches to vehicles, ATVs, golf carts, or other critical assets.
- Track Movements in Real-Time — Track and map (with Google Maps) in real-time on web-based software or our SilverCloud App. Location updates as fast as every 3 seconds with historical playback for up to 1 year.
- Powerful & Discreet — The motion-activated GPS tracker will sleep when not in motion for extended periods, preserving the battery life. The ultra-compact design and internal magnet create the ultimate discreet tracker.
- Lifetime Warranty — This GPS tracker is built to last. LandAirSea, a USA-based company and pioneer in GPS tracking offers a unconditional lifetime warranty that covers any manufacturing defects in the device encountered during normal use.
- Subscription Required — Affordable subscription plans are required for each device. Fees start as low as $9.95 a month for annual plans and $19.95 for monthly plans. No contracts, cancel anytime for a hassle-free experience.
Request a location estimate from Python
Python can call Google’s hosted Geolocation API over HTTPS. The service accepts a JSON request and returns fields including location.lat, location.lng, and accuracy. The request endpoint is Google’s documented geolocate endpoint; the placeholder key must be replaced with a credential configured for your application. The example below uses Python’s standard library, so it does not require an additional HTTP package.
import json
import os
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
api_key = os.environ.get("GOOGLE_GEOLOCATION_API_KEY")
if not api_key:
raise RuntimeError("Set GOOGLE_GEOLOCATION_API_KEY before running this script.")
url = f"https://www.googleapis.com/geolocation/v1/geolocate?key={api_key}"
payload = {
# Provide observations when your application has them:
# "wifiAccessPoints": [...],
# "cellTowers": [...],
# Google documents considerIp as true by default. Set it explicitly
# if you want the request's intended behavior to be clear.
"considerIp": True
}
request = Request(
url,
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json"},
method="POST",
)
try:
with urlopen(request, timeout=30) as response:
result = json.loads(response.read().decode("utf-8"))
except HTTPError as exc:
print("Geolocation service returned HTTP", exc.code)
print(exc.read().decode("utf-8", errors="replace"))
raise
except URLError as exc:
raise RuntimeError(f"Could not reach the geolocation service: {exc}") from exc
location = result["location"]
print("Latitude:", location["lat"])
print("Longitude:", location["lng"])
print("Accuracy radius in meters:", result["accuracy"])
Set the credential in the environment rather than committing it to source control; for example, configure GOOGLE_GEOLOCATION_API_KEY through your deployment platform’s secret store. Restrict API credentials appropriately. The service’s response is an estimate, and accuracy is a radius in meters—not a claim of exact coordinates.
Supplying Wi-Fi or cell observations
Google documents request fields for Wi-Fi access points, cell towers, and radio or network details. Include observations only when your application actually has them and can lawfully use them. Do not put invented, stale, or unrelated observations into the payload. The service documents considerIp as defaulting to true; when enabled, IP information may be considered as a fallback. IP-based estimates can be much less specific than device-derived observations.
Google’s documentation identifies Python among languages supported by its Maps web-service client libraries, but the documented client-library coverage list does not establish a dedicated Python wrapper for this Geolocation API endpoint. A direct HTTPS request, as above, is a straightforward implementation route; do not assume a particular official Python client exposes this endpoint.
Rank #3
- LONG-BATTERY VEHICLE TRACKING – Built for cars, trailers, fleets, equipment, boats, and motorcycles, Tracki’s trailer GPS tracker uses a 10,000mAh battery for 2 to 7 months active at 1–5 minute updates or up to 12 months in sleep mode.
- SUBSCRIPTION-POWERED SERVICE – The Tracki GPS tracker connects through 4G LTE Cat1 with built-in global SIM, giving app access, real-time location updates, alerts, and support after activation; Subscription Required, Cancel Anytime.
- FLEET-WIDE CONTROL – A practical fleet GPS tracker for work vehicles, with subscription-powered 15-second to 1-minute updates plus speed, geofence, movement, idle time, impact, and battery alerts through SMS, email, and app notifications.
- TRAILER & ASSET COVERAGE – A GPS tracker for trailer, car, truck, RV, boat, or equipment use, with 185+ country coverage, GPS accuracy of 5 to 10 meters outdoors, and Wi-Fi fallback indoors when GPS signals are harder to reach.
- SECURE TWO-WHEEL MONITORING – Use this motorcycle tracker for authorized bikes and powersport assets, with a built-in strong magnet, included screw mount, and weatherproof design for flexible vehicle placement.
Permission, privacy, credentials, and cost
Browser and hosted-service approaches have different operational responsibilities. Browser permission does not automatically resolve your application’s privacy obligations, and a server-side request does not make location collection invisible or exempt from those obligations.
- Explain the purpose. Request location only when it is needed for a user-facing feature. Give a useful explanation before triggering the browser prompt.
- Minimize retention. Avoid logging precise coordinates or keeping them longer than the feature requires. Protect location data in transit and at rest.
- Check service requirements. Google requires an API credential and enabled billing for its hosted Geolocation API. Before deployment, review current quotas, pricing, terms, privacy requirements, and attribution rules in Google’s documentation; those details can change.
- Do not expose secrets. A server-side Python key should be supplied through configuration or a secret manager and restricted as appropriate. Do not publish a working key in client-side code or a public repository.
Troubleshooting common failures
| Symptom | Likely cause | What to do |
|---|---|---|
navigator.geolocation is missing |
The browser or execution environment does not expose the API, or the page is not running in a supported secure context. | Check feature detection, test in a supported browser, and serve the deployed page over HTTPS. |
| Permission denied | The user declined the browser prompt or a browser/site policy blocks access. | Explain why location is useful and let the user change browser permission settings; do not repeatedly trigger prompts. |
| Position unavailable | The device or its available location sources could not produce a result. | Offer a manual alternative, such as entering a location, rather than treating failure as an application crash. |
| Timeout | The device did not deliver a position within the configured time. | Show a retry option or adjust the timeout to fit the feature. A longer wait does not ensure a more accurate position. |
| Python receives an HTTP error | The key may be missing or invalid, the API may not be enabled, billing may not be active, or the request may violate service requirements. | Inspect the HTTP status and response body without printing secrets; verify credential restrictions, API setup, billing, quota, and request JSON. |
| Python request succeeds but estimate is broad or unexpected | The service may have limited network observations and may rely on IP-based estimation. | Check which observations were submitted and inspect the returned accuracy radius. Do not present a broad estimate as an exact device location. |
Or skip the browser setup
ScreenshotNeo is a website screenshot API and MCP server, not a geolocation service; use the JavaScript or Python examples above when you need location. If your separate task is to capture a web page, one GET request can return an image or PDF. The example saves a screenshot of Stripe as WebP. See the ScreenshotNeo API documentation.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
- Cookie and consent banners, newsletter popups, and chat widgets can be removed before capture.
- Bot checks, blank pages, and failed loads are never billed.
- An MCP server lets AI agents use tools to take screenshots.
- 1,000 screenshots a month are free with no card; paid plans start at $5 for 3,000.
Learn about ScreenshotNeo or sign up for 1,000 free screenshots a month, with no card required.
Which implementation should you use?
Use browser geolocation when a visitor’s device should provide a location estimate and the user can grant permission in the browser. Use a hosted network-data API from Python when your application has relevant Wi-Fi or cell observations to submit, or needs the service’s documented IP-based behavior. In either case, design around uncertainty: show an accuracy radius where it matters, provide a fallback for failures, and collect only the location data the feature needs.
Rank #4
- Real-Time GPS Tracker Device for Vehicles — Ideal for personal use or fleet management, this car GPS tracker provides up-to-the-minute location updates. Our car tracking device also provides unlimited trip history, including a detailed route history
- Driving Insights — Our OBD tracker for cars monitors speed, acceleration, hard braking, idle time, and more. This versatile family and fleet GPS tracker for cars also helps improve road safety by sending alerts in response to unsafe driving practices
- Vehicle Health — Unlike other vehicle tracking devices, our car tracker device continuously monitors diagnostic engine data, alerting you to potential maintenance issues, so you can avoid downtime and keep fleet and family vehicles in peak condition
- Geo-Fencing & Accident Detection — Set up geo-fences to receive notifications when your vehicle enters or exits designated areas; Equipped with advanced sensors and software, this vehicle tracker device instantly detects impacts and sends SMS alerts
- Easy To Install & Low Monthly Subscription — Our OBD GPS tracker for vehicles plugs directly into OBD2 ports and works on most vehicles 1996 and newer; $9.65 monthly subscription required - no hidden activation or return fees - cancel anytime
Frequently Asked Questions
Does Python have a built-in equivalent of navigator.geolocation?
No. That object belongs to the browser environment. Python code can request an estimate from a separate service over HTTPS, or use an appropriate native or device-specific location facility when available.
Does a browser geolocation result prove the user is at those coordinates?
No. It is an estimate, and the API does not guarantee that the returned location is the device’s actual location.
Can I use Google Maps JavaScript to request the device position?
A map is optional. The browser’s Geolocation API can request a position without Google Maps; a map library can then display or center on that result.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problems

