HTML5 Geolocation « PreviousNext Chapter » HTML Geolocation is used to locate a user's position. Try It Locate the User's Position The HTML Geolocation API is used to get the geographical position of a user. Since this can compromise user privacy, the position is not available unless the user approves it. Browser Support The numbers in the table specify the first browser version that fully supports Geolocation. API Geolocation 5.0 9.0 3.5 5.0 16.0 Note: Geolocation is much more accurate for devices with GPS, like iPhone. Using HTML Geolocation Use the getCurrentPosition() method to get the user's position. The example below is a simple Geolocation example returning the latitude and longitude of the user's position: Example Try it yourself » Example explained: Check if Geolocation is supported If supported, run the getCurrentPosition() method. If not, display a message to the user If the getCurrentPosition() method is successful, it returns a coordinates object to the function specified in the parameter ( showPosition ) The showPosition() function gets the displays the Latitude and Longitude The example above is a very basic Geolocation script, with no error handling. Handling Errors and Rejections The second parameter of the getCurrentPosition() method is used to handle errors. It specifies a function to run if it fails to get the user's location: Example function showError(error) { switch(error.code) { case error.PERMISSION_DENIED: x.innerHTML = "User denied the request for Geolocation." break; case error.POSITION_UNAVAILABLE: x.innerHTML = "Location information is unavailable." break; case error.TIMEOUT: x.innerHTML = "The request to get user location timed out." break; case error.UNKNOWN_ERROR: x.innerHTML = "An unknown error occurred." break; } } Try it yourself » Error Codes: Permission denied - The user did not allow Geolocation Position unavailable - It is not possible to get the current location Timeout - The operation timed out Displaying the Result in a Map To display the result in a map, you need access to a map service that can use latitude and longitude, like Google Maps: Example function showPosition(position) { var latlon = position.coords.latitude + "," + position.coords.longitude; var img_url = "http://maps.googleapis.com/maps/api/staticmap?center= "+latlon+"&zoom=14&size=400x300&sensor=false"; document.getElementById("mapholder").innerHTML = "