Error and Rejection Handling
It is very important to handle the errors generated in Geolocation and show a required message when an error occurs. Functions like getCurrentPosition() make use of an error handler to handle the error generated (function errHand as used in the above example). The PositionError object used by the error handler has two properties that let the function handle error efficiently.
- Code
- Message
Generated errors in geolocation:
Error | Error Description |
---|---|
UNKNOWN_ERRROR | An unknown error |
PERMISSION_DENIED | The application doesn’t have permission to make use of location services |
POSITION_UNAVAILABLE | The location of the device is uncertain |
TIMEOUT | The time to fetch location information exceeded the maximum timeout interval |
Example: In this example we will see the implementation of geo location in HTML document.
HTML
<!DOCTYPE html> < html > < head > < title >Errors in geolocation</ title > < style > .gfg { font-size: 40px; font-weight: bold; color: #009900; margin-left: 20px; } .geeks { margin-left: 150px; } p { font-size: 20px; margin-left: 20px; } </ style > </ head > < body > < div class = "gfg" >w3wiki</ div > < p >Error handling in geolocation</ p > < button class = "geeks" onclick = "getlocation()" > Click </ button > < p id = "demo1" ></ p > < script > var variable1 = document.getElementById("demo1"); function getlocation() { navigator.geolocation.getCurrentPosition(showLoc, errHand); } function showLoc(pos) { variable1.innerHTML = "Latitude: " + pos.coords.latitude + "< br >Longitude: " + pos.coords.longitude; } function errHand(err) { switch (err.code) { case err.PERMISSION_DENIED: variable1.innerHTML = "The application doesn't have the" + "permission to make use of location services"; break; case err.POSITION_UNAVAILABLE: variable1.innerHTML = "The location of the device is uncertain"; break; case err.TIMEOUT: variable1.innerHTML = "The request to get user location timed out"; break; case err.UNKNOWN_ERROR: variable1.innerHTML = "Time to fetch location information exceeded" + "the maximum timeout interval"; break; } } </ script > </ body > </ html > |
Output:
HTML Geolocation
The HTML Geolocation is used to get the geographical position of a user. Due to privacy concerns, this position requires user approval. Geo-location in HTML5 is used to share the location with some websites and be aware of the exact location. It is mainly used for local businesses, and restaurants, or showing locations on the map. It uses JavaScript to give latitude and longitude to the backend server.
Most browsers support Geolocation API. Geo-location API uses a global navigator object. In this article, we will know HTML Geolocation, various properties, methods & their implementation through examples.