Create Online Attendance by Retrieving User Location with Leaflet JS

Create Online Attendance by Retrieving User Location with Leaflet JS
Hello everyone, back again at porkaone. On this occasion, we will learn how to create a simple attendance that takes advantage of the user's location and uses a js leaflet to display location maps. Intrigued?, let's follow the tutorial below.





On this occasion, we will create a simple attendance application where every user who makes attendance records will be stored in a database of date, time, name, latitude and longitude. We will also render a map with the leaflet js library. So every user who makes attendance, their location is also automatically known, the system will also refuse if the GPS system is not turned on.



Create Online Attendance by Retrieving User Location with Leaflet JS

1. Create a new database with the name practice, then create a table in it with the name attendance_online or with the name you want. Follow the table structure as shown below.

Absensi Online PHP
Online Attendance Table







2. Create a new folder with the name attendance_online, then create an index.php file in it and fill the file with the script as shown below.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta name="Description" content="Enter your description here" /> <!-- bootstrap css library --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.0/css/bootstrap.min.css"> <!-- leaflet css --> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="" /> <title>Sahretech Tutorial</title> <style> #mapid { aspect-ratio: 1/1; width: 100%; border-radius: 10px; z-index: 0; } </style> </head> <body> <div class="container mt-4"> <h3 class="alert alert-info text-center">Online Attendace With Leaflet JS</h3> <!-- make 2 column, left column for attendace input and right column for table --> <div class="row"> <div class="col-lg-4"> <div class="card"> <div class="card-body"> fill your name, and click the submit button to make an online attendance <br><br> <!-- fill the name field, and click submit button to add record the data will be send to process.php --> <form method="post" action="process.php"> <label>Name</label> <input type="text" name="name" class="form-control mt-1" required placeholder="Type Your Name"> <!-- latitude and longitude automatically filled when page loaded. we use javascript for get latitude and longitude with device gps. if latitude and longitude empty, form cannot be submitted. You have to check whether the GPS is blocked or not --> <label class="mt-4">Latitude</label> <input type="text" name="latitude" class="form-control mt-1" required readonly id="latitude"> <label class="mt-4">Latitude</label> <input type="text" name="longitude" class="form-control mt-1" required readonly id="longitude"> <button class="btn btn-primary mt-4" type="submit">Submit</button> </form> </div> </div> </div> <div class="col-lg-8"> <!-- The stored data will be displayed here. --> <table class="table table-striped"> <tr> <th>No</th> <th>Name</th> <th>Lat</th> <th>Long</th> <th>Time</th> <th>Map</th> </tr> <?php //make index variabel $num = 1; //make connection to database $connect = mysqli_connect('localhost', 'root', '', 'latihan'); //after the connection is established, retrieve the attendance data from the table $select = mysqli_query($connect, "select * from online_attendance"); //loop data with while() while($data= mysqli_fetch_array($select)){ ?> <tr> <!-- show data with array --> <td><?php echo $num++; ?></td> <td><?php echo $data['name']; ?></td> <td><?php echo $data['latitude']; ?></td> <td><?php echo $data['longitude']; ?></td> <td><?php echo $data['time']; ?></td> <!-- we add button, when button clicked, map will be displayed to see how popup and map can show you can see the javascript function --> <td> <button onclick="showMap(<?php echo $data['latitude']; ?>, <?php echo $data['longitude']; ?>)" class="btn btn-primary btn-sm"> Location</button> </td> </tr> <?php } ?> </table> <!-- map will be displayed here --> <div class="card"> <div class="card-body"> <h5 class="alert alert-info text-center">Map will be displayed in this area, click the button location in table to see the map location</h5> <div id="mapid"></div> </div> </div> </div> </div> </div> <!-- bootstrap js library --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.9.2/umd/popper.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.1.0/js/bootstrap.min.js"></script> <!-- leaflet js --> <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script> <script> // javascript function to get longitude and latitude function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition, showError); } else { alert('Your device is not support!'); } } // fill the latitude and longitude form with this function function showPosition(data) { document.getElementById('latitude').value = data.coords.latitude document.getElementById('longitude').value = data.coords.longitude } // javascript function to show error function showError(error) { let error_message = '' switch (error.code) { case error.PERMISSION_DENIED: error_message = "User denied the request for Geolocation." break; case error.POSITION_UNAVAILABLE: error_message = "Location information is unavailable." break; case error.TIMEOUT: error_message = "The request to get user location timed out." break; case error.UNKNOWN_ERROR: error_message = "An unknown error occurred." break; } alert(error_message) } var mymap = '' function showMap(latitude, longitude) { //remove map and render the new map if (mymap) { mymap.remove(); mymap = undefined } //make map area mymap = L.map("mapid").setView( [latitude, longitude], 13 ); //setting maps using api mapbox not google maps, register and get tokens L.tileLayer( "https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw", { maxZoom: 18, attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' + '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' + 'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>', id: "mapbox/streets-v11", tileSize: 512, zoomOffset: -1, } ).addTo(mymap); //add marker position with variabel latitude and longitude L.marker([ latitude, longitude ]) .addTo(mymap) .bindPopup("Location"); } getLocation() </script> </body> </html>




3. Next, create a new file with the name process.php in a folder with index.php. Then follow the script as shown below.

<?php //make connection to database $connect = mysqli_connect('localhost', 'root', '', 'latihan'); //get data from form input $name = $_POST['name']; $latitude = $_POST['latitude']; $longitude = $_POST['longitude']; $time = date("Y-m-d H:i:s"); //insert data into database $insert = mysqli_query($connect, "insert into online_attendance set name='$name', latitude='$latitude', longitude='$longitude', time='$time'"); //back to index.php header("Location: index.php"); ?>




If all the steps above have been carried out correctly, then it's time for us to do a trial run. Please open a browser and type localhost/attendance_online. If successful, it will look like the image below.

Tampilan Akhir Absensi Online
Final Result





This tutorial is very simple, you can improvise by adding logins, time attendance status, employee dropdown list statistics, and many other features.


That's all for our tutorial this time about how to create an online attendance by taking the user's location using the js leaflet. Hopefully this tutorial is useful. If you have questions, please ask directly in the comments column below. That is all and thank you

Post a Comment

0 Comments