System Information, Geolocation and Battery Monitoring using JavaScript

System Information, Geolocation and Battery Monitoring using JavaScript

In this tutorial, we are going to take a deep dive into an HTML page that pulls system and device information along with geolocation data. The goal of this project is to demonstrate how we can access and display useful device statistics, such as device type, battery status, and geolocation, using modern web technologies like JavaScript and the HTML5 APIs. Furthermore, we will utilize Leaflet, a popular open-source JavaScript library, to display the user’s location on a map. We will also incorporate Bootstrap for responsive design, making this tool look clean and professional.

Overview of the Webpage Structure

The webpage in question is a simple yet powerful tool that displays system and device information to the user, including:

  • Device Information such as user agent, platform, RAM, CPU cores, and device type.
  • Battery Information (if available), showing whether the device is charging and its battery level.
  • Geolocation information, which is displayed on an interactive map using the Leaflet JavaScript library.

This information can be highly valuable in various situations, such as system diagnostics, web application development, or troubleshooting device issues. By utilizing the HTML5 APIs and JavaScript, we can easily retrieve and display this data.

Follow this video for complete guidance :

HTML Structure and Bootstrap Layout

The HTML structure uses standard elements with Bootstrap for styling. Bootstrap ensures that the design is responsive, and the layout adjusts itself across different screen sizes.

Here’s a breakdown of the structure:

  • Container: The container is used to encapsulate the content and provides padding around the page.
  • Header: The page has a header that displays the title “System & Device Information”. The title is styled using Bootstrap’s utility classes for typography and alignment.
  • Two-Column Layout: Inside the container, we create a row with two columns, one for device details and one for geolocation.
    • Device Details: This column contains a list of details about the device, such as the user agent, platform, available RAM, number of CPU cores, device type, and battery status.
    • Geolocation: This column displays an interactive map with the user’s location, which will be rendered by Leaflet.

Let’s move on to the functionality implemented via JavaScript.

Accessing Device Information

User Agent

The user agent string is a piece of information provided by the browser that gives insight into the browser and operating system being used. This information is useful for detecting the browser type, version, and device platform. In the code, we access the navigator.userAgent property, which contains the full user agent string of the browser. The string is displayed in the “Device Details” section of the webpage.

$("#userAgent").text(navigator.userAgent);

Platform

The navigator.platform property provides information about the platform on which the browser is running, such as Windows, macOS, Android, or iOS. This is another helpful piece of data for web developers who want to tailor their applications for specific platforms.

$("#platform").text(navigator.platform);

RAM

The navigator.deviceMemory property tells us the approximate amount of device RAM in gigabytes. This can be useful for developers optimizing their applications, particularly for mobile devices where memory resources are limited. If the browser does not support this API, the script will display “Unknown.”

$("#ram").text((navigator.deviceMemory || "Unknown") + (navigator.deviceMemory ? " GB" : ""));

CPU Cores

The navigator.hardwareConcurrency property gives the number of logical processor cores on the device. This helps developers understand the available processing power and optimize performance accordingly. For instance, if a device has a low number of CPU cores, a developer may choose to avoid intensive operations.

$("#cpu").text(navigator.hardwareConcurrency || "Unknown");

Device Type

We determine the device type (whether it is a mobile/tablet or desktop) by examining the user agent string. If the string matches certain patterns like Mobi or Android, the device is classified as a mobile or tablet; otherwise, it is classified as a desktop.

$("#deviceType").text(/Mobi|Android/i.test(navigator.userAgent) ? "Mobile/Tablet" : "Desktop");

Battery Information

Battery information is fetched using the navigator.getBattery() method. This API returns a BatteryManager object that provides details about the device’s battery level and charging status. The information is displayed dynamically, with the percentage and charging status updated as the battery’s state changes.

if (navigator.getBattery) {
    navigator.getBattery().then(function(battery) {
        $("#battery").text(`${(battery.level * 100).toFixed(0)}% ${battery.charging ? "(Charging)" : "(Not Charging)"}`);
    });
} else {
    $("#battery").text("Not available");
}

Geolocation

The geolocation feature leverages the navigator.geolocation API, which allows web applications to retrieve the user’s current geographical location (latitude and longitude). This is particularly useful for location-based services, such as mapping applications or geotagging.

Using this API, the webpage gets the user’s position and then integrates Leaflet to display that position on an interactive map. Here’s a quick overview of the process:

  • First, we check if geolocation is supported by the user’s browser.
  • If supported, we use the navigator.geolocation.getCurrentPosition() method to fetch the user’s coordinates.
  • If successful, we initialize a Leaflet map centered at the user’s latitude and longitude and place a marker at that location.
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
        function(position) {
            let map = L.map('map').setView([position.coords.latitude, position.coords.longitude], 13);
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '© OpenStreetMap contributors'
            }).addTo(map);
            L.marker([position.coords.latitude, position.coords.longitude]).addTo(map)
                .bindPopup("You are here!").openPopup();
        },
        function() {
            $("#map").html("<div class='alert alert-warning'>Geolocation permission denied!</div>");
        }
    );
} else {
    $("#map").html("<div class='alert alert-warning'>Geolocation is not supported by your browser.</div>");
}

Leaflet Integration

Leaflet is an open-source JavaScript library designed to create interactive maps. In this tutorial, Leaflet is used to render the user’s location on a map. The map tiles are sourced from OpenStreetMap, and a marker is placed at the current location. The L.map() function initializes the map, and L.tileLayer() adds the tile layer. Markers are added with L.marker().

The map is displayed within a <div> element that is styled with CSS to ensure it has a proper height, which is crucial for Leaflet to render the map correctly.

#map { height: 300px; }

Error Handling and User Experience

To enhance the user experience, we handle cases where geolocation is not supported or the user denies the geolocation permission. In both cases, the page will display a warning message informing the user of the issue. This ensures that users are aware of any limitations in functionality.

$("#map").html("<div class='alert alert-warning'>Geolocation is not supported by your browser.</div>");

Full Source Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>System & Device Info</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Leaflet CSS -->
    <link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
    <style>
        #map { height: 300px; }
    </style>
</head>
<body class="bg-light">
    <div class="container py-4">
        <header class="pb-3 mb-4 border-bottom">
            <h1 class="display-5 text-center fw-bold text-primary">System & Device Information</h1>
        </header>

        <div class="row g-4">
            <div class="col-md-6">
                <div class="card shadow-sm h-100">
                    <div class="card-header bg-primary text-white">
                        <h4 class="my-0">Device Details</h4>
                    </div>
                    <div class="card-body">
                        <ul class="list-group list-group-flush">
                            <li class="list-group-item d-flex justify-content-between">
                                <span id="userAgent" class="text-muted text-truncate ms-2"></span>
                            </li>
                            <li class="list-group-item d-flex justify-content-between">
                                <strong>Platform:</strong> <span id="platform" class="text-muted"></span>
                            </li>
                            <li class="list-group-item d-flex justify-content-between">
                                <strong>RAM (Approx.):</strong> <span id="ram" class="text-muted"></span>
                            </li>
                            <li class="list-group-item d-flex justify-content-between">
                                <strong>CPU Cores:</strong> <span id="cpu" class="text-muted"></span>
                            </li>
                            <li class="list-group-item d-flex justify-content-between">
                                <strong>Device Type:</strong> <span id="deviceType" class="text-muted"></span>
                            </li>
                            <li class="list-group-item d-flex justify-content-between">
                                <strong>Battery:</strong> <span id="battery" class="text-muted"></span>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>

            <div class="col-md-6">
                <div class="card shadow-sm">
                    <div class="card-header bg-primary text-white">
                        <h4 class="my-0">Your Location</h4>
                    </div>
                    <div class="card-body p-0">
                        <div id="map" class="rounded"></div>
                    </div>
                </div>
            </div>
        </div>

    
    </div>

    <!-- JQuery -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <!-- Leaflet JS -->
    <script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Device Information
            $("#userAgent").text(navigator.userAgent);
            $("#platform").text(navigator.platform);
            $("#ram").text((navigator.deviceMemory || "Unknown") + (navigator.deviceMemory ? " GB" : ""));
            $("#cpu").text(navigator.hardwareConcurrency || "Unknown");
            $("#deviceType").text(/Mobi|Android/i.test(navigator.userAgent) ? "Mobile/Tablet" : "Desktop");
            
            // Battery Info
            if (navigator.getBattery) {
                navigator.getBattery().then(function(battery) {
                    $("#battery").text(`${(battery.level * 100).toFixed(0)}% ${battery.charging ? "(Charging)" : "(Not Charging)"}`);
                });
            } else {
                $("#battery").text("Not available");
            }
            
            // Geolocation
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    function(position) {
                        
                        let map = L.map('map').setView([position.coords.latitude, position.coords.longitude], 13);
                        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                            attribution: '© OpenStreetMap contributors'
                        }).addTo(map);
                        L.marker([position.coords.latitude, position.coords.longitude]).addTo(map)
                            .bindPopup("You are here!").openPopup();
                    }, 
                    function() {
                        $("#map").html("<div class='alert alert-warning'>Geolocation permission denied!</div>");
                    }
                );
            } else {
                $("#map").html("<div class='alert alert-warning'>Geolocation is not supported by your browser.</div>");
            }
        });
    </script>
</body>
</html>

This simple yet powerful webpage demonstrates how you can gather and display essential system and device information in real-time. The use of modern web technologies like HTML5 APIs, Leaflet, and Bootstrap enables developers to create interactive, dynamic web applications that provide valuable insights into the user’s environment.

By understanding how to retrieve and display system details such as the device’s user agent, platform, RAM, CPU, battery status, and geolocation, developers can create applications that are more context-aware and responsive to the needs of users. These techniques have a wide range of use cases, from optimizing web applications for specific devices to enhancing user experience by providing location-based services.

Overall, the combination of JavaScript, HTML5, and external libraries like Leaflet makes this task relatively easy to implement while providing significant functionality to any modern web application.

Related Posts