Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active February 18, 2024 17:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/02322e23cd897cabb337c0dd913fc053 to your computer and use it in GitHub Desktop.
Save code-boxx/02322e23cd897cabb337c0dd913fc053 to your computer and use it in GitHub Desktop.
PHP MYSQL GPS Tracking

PHP MYSQL GPS TRACKING SYSTEM

https://code-boxx.com/gps-tracking-system-php-javascript/

NOTES

  1. Create a database and import 1-database.sql.
  2. Change the database settings in 2-lib-track.php to your own.
  3. Access 4a-track.html for the client/rider tracking page, and 4b-admin.html for the demo admin page.
  4. Take extra note that GPS geolocation requires https:// to work properly. http://localhost is an exception for testing.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

CREATE TABLE `gps_track` (
`rider_id` bigint(20) NOT NULL,
`track_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`track_lng` decimal(11,7) NOT NULL,
`track_lat` decimal(11,7) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `gps_track`
ADD PRIMARY KEY (`rider_id`),
ADD KEY `track_time` (`track_time`);
<?php
class Track {
// (A) CONSTRUCTOR - CONNECT TO DATABASE
public $pdo = null;
public $stmt = null;
public $error = "";
function __construct () {
$this->pdo = new PDO(
"mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET,
DB_USER, DB_PASSWORD, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
}
// (B) DESTRUCTOR - CLOSE CONNECTION
function __destruct () {
if ($this->stmt !== null) { $this->stmt = null; }
if ($this->pdo !== null) { $this->pdo = null; }
}
// (C) HELPER FUNCTION - EXECUTE SQL QUERY
function query ($sql, $data=null) : void {
$this->stmt = $this->pdo->prepare($sql);
$this->stmt->execute($data);
}
// (D) UPDATE RIDER COORDINATES
function update ($id, $lng, $lat) {
$this->query(
"REPLACE INTO `gps_track` (`rider_id`, `track_time`, `track_lng`, `track_lat`) VALUES (?,?,?,?)",
[$id, date("Y-m-d H:i:s"), $lng, $lat]
);
return true;
}
// (E) GET RIDER(S) COORDINATES
function get ($id=null) {
$this->query(
"SELECT * FROM `gps_track`" . ($id==null ? "" : " WHERE `rider_id`=?"),
$id==null ? null : [$id]
);
return $this->stmt->fetchAll();
}
}
// (F) DATABASE SETTINGS - CHANGE THESE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8mb4");
define("DB_USER", "root");
define("DB_PASSWORD", "");
// (G) START!
$_TRACK = new Track();
<?php
if (isset($_POST["req"])) {
require "2-lib-track.php";
switch ($_POST["req"]) {
// (A) UPDATE RIDER LOCATION
case "update":
echo $_TRACK->update($_POST["id"], $_POST["lng"], $_POST["lat"])
? "OK" : $_TRACK->error ;
break;
// (B) GET RIDER(S) LAST KNOWN LOCATION
case "get":
echo json_encode($_TRACK->get(isset($_POST["id"]) ? $_POST["id"] : null));
break;
}
}
<!DOCTYPE html>
<html>
<head>
<title>Geolocation Tracking Demo</title>
<meta charset="utf-8">
<link rel="stylesheet" href="X-demo.css">
<script src="4a-track.js"></script>
</head>
<body>
<div class="row">
<div class="title">Updated</div>
<div class="data" id="date"></div>
</div>
<div class="row">
<div class="title">Latitude, Longitude</div>
<div class="data">
<span id="lat"></span>, <span id="lng"></span>
</div>
</div>
</body>
</html>
var track = {
// (A) INIT
rider : 999, // rider id - fixed to 999 for demo
delay : 10000, // delay between gps update (ms)
timer : null, // interval timer
hDate : null, // html date
hLat : null, // html latitude
hLng : null, // html longitude
init : () => {
// (A1) GET HTML
track.hDate = document.getElementById("date");
track.hLat = document.getElementById("lat");
track.hLng = document.getElementById("lng");
// (A2) START TRACKING
track.update();
track.timer = setInterval(track.update, track.delay);
},
// (B) SEND CURRENT LOCATION TO SERVER
update : () => navigator.geolocation.getCurrentPosition(
pos => {
// (B1) LOCATION DATA
var data = new FormData();
data.append("req", "update");
data.append("id", track.rider);
data.append("lat", pos.coords.latitude);
data.append("lng", pos.coords.longitude);
// (B2) AJAX SEND TO SERVER
fetch("3-ajax-track.php", { method:"POST", body:data })
.then(res => res.text())
.then(txt => { if (txt=="OK") {
let now = new Date();
track.hDate.innerHTML = now.toString();
track.hLat.innerHTML = pos.coords.latitude;
track.hLng.innerHTML = pos.coords.longitude;
} else { track.error(txt); }})
.catch(err => track.error(err));
},
err => track.error(err)
),
// (C) HELPER - ERROR HANDLER
error : err => {
console.error(err);
alert("An error has occured, open the developer's console.");
clearInterval(track.timer);
}
};
window.onload = track.init;
<!DOCTYPE html>
<html>
<head>
<title>GPS Tracking Demo</title>
<meta charset="utf-8">
<link rel="stylesheet" href="X-demo.css">
<script src="4b-admin.js"></script>
</head>
<body>
<div id="wrapper"></div>
</body>
</html>
var track = {
// (A) INIT
delay : 10000, // delay between location refresh
timer : null, // interval timer
hWrap : null, // html <div> wrapper
init : () => {
track.hWrap = document.getElementById("wrapper");
track.show();
track.timer = setInterval(track.show, track.delay);
},
// (B) GET DATA FROM SERVER AND UPDATE MAP
show : () => {
// (B1) DATA
var data = new FormData();
data.append("req", "get");
// (B2) AJAX FETCH
fetch("3-ajax-track.php", { method:"POST", body:data })
.then(res => res.json())
.then(data => { for (let r of data) {
let row = document.createElement("div");
row.className = "row";
row.innerHTML =
`<div class="title">[${r.track_time}] Rider ${r.rider_id}</div>
<div class="data">${r.track_lat}, ${r.track_lng}</div>`;
track.hWrap.appendChild(row);
}})
.catch(err => track.error(err));
},
// (C) HELPER - ERROR HANDLER
error : err => {
console.error(err);
alert("An error has occured, open the developer's console.");
clearInterval(track.timer);
}
};
window.onload = track.init;
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
body { background: #f2f2f2; }
.row {
margin-bottom: 10px;
padding: 10px;
border: 1px solid #e1e1e1;
background: #fff;
}
.title {
text-transform: uppercase;
font-size: 1.2em;
margin-bottom: 5px;
}
.data {
color: #ff2d2d;
font-size: 0.9em;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment