HTML5 Native APIs

Learn how to access device functionalities like Geolocation directly from the browser.

HTML5 Native APIs

HTML5 introduced powerful APIs that let web pages interact with device hardware, like your location. Let's explore the Geolocation API.

What are HTML5 APIs?

HTML5 introduced a set of native Application Programming Interfaces (APIs) that allow web apps to interact with device hardware and the operating system without external plugins. This includes access to cameras, microphones, and location services.

The Geolocation API

The Geolocation API provides a simple way to get the geographical position of a user's device. Access is provided through the navigator.geolocation object. For privacy reasons, the user is always asked for permission to share their location.

Getting the Current Position

The most common method is getCurrentPosition(). It takes a callback function that receives a Position object, which contains coordinates like latitude and longitude.

Practice Zone


Practice Example: Code Editor

Implement a simple application using the HTML5 Geolocation API. It should allow the user to get their current location and display the latitude and longitude on the screen.

* Write the code below. Correct characters will be shown in green and incorrect ones in red.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Geolocation Example</title> </head> <body> <button onclick="getLocation()">Get Location</button> <p id="demo"></p> <script> function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { document.getElementById("demo").innerHTML = "Geolocation is not supported by this browser."; } } function showPosition(position) { document.getElementById("demo").innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude; } </script> </body> </html>

Knowledge Check

Which of the following is a native API in HTML5?