Every "show me places near me" button on the web runs on one small API: navigator.geolocation. It is also an API surrounded by myths, starting with its name in most tutorials. The browser does not hand your code the GPS receiver; it hands you the device's best position, computed by the operating system from whatever it has: satellite GPS on a phone outdoors, Wi-Fi positioning in a city, cell towers, or a rough network estimate on a desktop. Build with that honesty and the API is simple and reliable. This guide writes the complete feature, explains every option and error, and flags the deployment rules that break location on production sites. For what the resulting pair means and how to restyle it, see latitude and longitude format.
Home / GPS and Navigation Guides
GPS Location in JavaScript: The Geolocation API, Worked End to End

Photo: Markus Winkler / Pexels
Geolocation in Code: The Build Order
Check off each step as you finish it. Your progress stays on this page.
0 of 7 complete
0% done
The Shape of the API: Three Methods, One Object
The API lives on navigator.geolocation and offers exactly three methods. getCurrentPosition(success, error, options) asks for the position once. watchPosition(success, error, options) asks repeatedly and returns a watch ID; it calls your success function every time the position changes. clearWatch(id) stops a watch. Nothing returns a position directly: the call is asynchronous, because radios take time, and the answer arrives in your success callback as a GeolocationPosition object with two parts: coords (the data) and timestamp (when the fix was taken, which matters more than beginners expect, since a cached fix can be minutes old). The coords object carries latitude, longitude, and accuracy in meters, plus altitude, altitudeAccuracy, heading, and speed, which are null whenever the device cannot supply them, as most desktops cannot.
The Minimal Working Call, Written Properly
Feature detect first, because old browsers and insecure pages may lack the API entirely:
```
if (!('geolocation' in navigator)) {
showMessage('Location is not available in this browser.');
} else {
navigator.geolocation.getCurrentPosition(onSuccess, onError, {
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
});
}
```
Three habits separate this from the copy paste version. It checks support before calling. It passes an error callback, because permission denial is a normal outcome, not an exception. And it sets options deliberately, the subject of the next section. Trigger the call from a button click or another clear user action, never silently on page load: browsers show a permission prompt, and a prompt that arrives with no context gets denied, and a denied permission is sticky. Explain in the page, in one sentence, why the location is needed and what it will be used for, next to the button that asks.
The Three Options, and What Each Really Costs
enableHighAccuracy: true asks the device to use its most precise source, on a phone that means powering the GPS receiver. The result is a slower first fix and more battery drain, in exchange for meters instead of hundreds of meters. Use it for navigation, check ins, and anything where the position is the product; leave it false for "which city is this" features. timeout is how long, in milliseconds, the API may take before giving up with a TIMEOUT error; 10 seconds is a sane default, and infinity is a bug that leaves users staring at a spinner while a phone hunts satellites indoors. maximumAge is how old a cached position may be and still be accepted: 0 demands a fresh fix every time, while a few minutes is fine for weather or store finders and makes repeat calls instant. Most production bugs trace to one of these three being left at a default the developer never chose: the checklist at the top of this page exists to make you choose.

Errors: The Whole Table
Your error callback receives a GeolocationPositionError with a code and a message. Code 1, PERMISSION_DENIED: the user, the browser setting, or a Permissions Policy said no. Your response should be a graceful fallback (ask for a city or a postal code) and instructions for re enabling, because you cannot re prompt from code. Code 2, POSITION_UNAVAILABLE: the device could not determine a position at all, common indoors, in airplane mode, or with location services off at the system level; suggest moving or checking the system toggle. Code 3, TIMEOUT: no fix within your timeout; retrying once with enableHighAccuracy relaxed or a longer timeout is reasonable, looping forever is not. Handle all three with distinct messages. "Location failed" teaches the user nothing; "the browser blocked location for this site; here is how to allow it" rescues the session.
watchPosition: Tracking Movement Without Burning the Battery
For a moving user, watchPosition replaces polling: the browser calls you when the position changes, at a rhythm it controls. Store the returned ID and call clearWatch(id) when the feature closes, the page hides, or the user stops the tracking, because a forgotten watch keeps the GPS warm and the battery draining. Expect the callback to fire with small jitters while the user stands still, since each fix is an estimate; smooth by ignoring updates whose movement is smaller than their own accuracy radius. Pair the watch with the timestamp on each position to drop out of order or stale fixes. This is the entire technical core behind live tracking pages like the ones map apps ship natively; the phone side of the same ideas, from the user's seat, is in how does gps work.
Accuracy: The Number Everyone Misreads
coords.accuracy is a radius in meters: the true position is expected to lie within that circle around the reported pair. The W3C specification defines the value at a 95 percent confidence level. Two disciplines follow. Always display or log the accuracy alongside the pair; a latitude and longitude quoted without it is a claim you cannot support, and a fix reporting 2,500 meters of accuracy is a city guess wearing coordinate clothing. And never average or filter positions without weighting by accuracy, since a 10 meter fix and a 900 meter fix are not votes of equal weight. Where the fix comes from explains its size: satellite fixes outdoors reach single digit meters on modern phones (GPS.gov quotes about 4.9 meters for a smartphone in open sky), Wi-Fi positioning in cities lands in the tens of meters, and network estimates can sprawl to kilometers. Your code cannot choose the source; it can only ask for high accuracy and then respect the radius it was given. The user's side of this same coin is coordinates of my location.
The Deployment Rules That Break Location in Production
Three gates decide whether any of the above runs at all. Secure context: geolocation only works on pages served over HTTPS (with localhost treated as trustworthy for development), so a page that worked on your machine fails silently on an insecure staging URL. Permission state: browsers remember a denial per site; the Permissions API (navigator.permissions.query with name 'geolocation') lets you check for 'denied' and show instructions instead of a dead button. Embedding policy: a page inside an iframe needs the iframe to carry an allow="geolocation" attribute, or every call inside it is denied by policy. Test on a real phone over the real network before shipping; desktop Chrome on a wired connection, located by its network, is the most misleading test environment this API has.
Putting the Pair to Work: Maps, Distances, and Honest Limits
A position your code receives is usually an intermediate, not an answer: the user wants the nearest store, the distance home, the marker on the map. The pair drops directly into any map library as the center and the marker (the pattern in how to use openstreetmap in website accepts a latitude and longitude and asks no questions), and distances from it are a haversine away, the same computation our how to find coordinates between two points guide works by hand. Two limits deserve repeating at the point of use. The position is the device's, which for a desktop user may be their network's egress city rather than their chair, so interfaces should confirm rather than assume ("Showing results near X" with an edit affordance beats silent certainty). And the position is perishable: a fix taken at page load describes where the device was, and a delivery driver, a train passenger, or a phone in a moving car has left it behind; features that depend on current position should watch it or re ask, with the user's knowledge, rather than quietly aging. Code that respects those two truths, device not person, moment not forever, is most of what separates a location feature from a location bug.
Related Guides
If this page answered part of the question, these GPS and navigation guides cover the rest of the same ground:
- GPS Location Joystick: How Android Mock Locations Work, and Their Honest Limits: A GPS joystick app does not hack your phone's satellite receiver.
- GPS Location QR Code: How to Make a QR Code That Opens Your Exact Spot on a Map: A QR code can carry a location as a geo URI, and any phone that scans it lands on your exact spot in its map app.
- Phone Location Wrong Country: When GPS Says Home and Your Apps Say Abroad: A phone can be right and wrong about its country at the same time, because it keeps two locations: the GPS position, computed from satellites, and...
Frequently Asked Questions
How do I get the user's GPS location in JavaScript?
Call navigator.geolocation.getCurrentPosition with a success callback, an error callback, and options. The success callback receives a position whose coords.latitude and coords.longitude are the pair, in decimal degrees. The page must be served over HTTPS, and the user must grant the browser's permission prompt.
Is the position from the Geolocation API really GPS?
Not necessarily. The browser returns the device's best position from whatever sources the operating system offers: GPS satellites on a phone outdoors, Wi-Fi positioning, cell towers, or network estimates on a desktop. Read coords.accuracy to judge each fix; it tells you the radius in meters the position is good to.
Why does geolocation work on localhost but not on my site?
Because browsers restrict the API to secure contexts. Localhost is treated as trustworthy for development, but a production or staging page over plain HTTP is not, and calls fail or the API is absent. Serve the page over HTTPS and the same code works.
What do the geolocation error codes mean?
Code 1 is PERMISSION_DENIED, the user or a policy refused. Code 2 is POSITION_UNAVAILABLE, the device could not produce a fix, as indoors or with system location off. Code 3 is TIMEOUT, no fix within the timeout you set. Give each its own message and recovery step in the interface.
How do I track a moving user in JavaScript?
Use watchPosition instead of repeated getCurrentPosition calls. It invokes your callback whenever the position changes and returns an ID; call clearWatch with that ID when tracking stops. Filter jitter by ignoring movements smaller than the fix's own accuracy radius.
Photo credits: Markus Winkler (Pexels); Rashed Paykary (Pexels). Photos are served from this site; follow the credit to the library page for the original.