Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Create a GPS Tracking System With PHP and Javascript

INTRODUCTION
WEB TRACKING MAGIC

Welcome to a tutorial on how to create a Gps Tracking system with PHP and Javascript. Once upon a time in the dark ages of the Internet, GPS is hardly known, and people really didn’t bother about it very much. It was not until the invention of smartphones (and the GPS units inside them), that some smart monkeys realize how useful it is.

Tracking where the vehicle is at, when the next bus is coming, where the order is it, or just making sure that people have actually delivered to the right place. The possibilities are endless, and it is not just limited to the native apps – It is also possible to create web apps using PHP and Javascript. Read on to find out how.

I have included a zip file with all the source code at the end of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

CONFESSION
AN HONEST DISCLOSURE

Quick, hide your wallets! I am an affiliate partner of Google, eBay, Adobe, Bluehost, Clickbank, and more. There are affiliate links and advertisements throughout this website. Whenever you buy things from the evil links that I recommend, I will make a commission. Nah. These are just things to keep the blog going, and allows me to give more good stuff to you guys - for free. So thank you if you decide to pick up my recommendations!


 

NAVIGATION
TABLE OF CONTENTS

Prelude
Overview & Assumptions

Step 1
The Database

Step 2
Endpoint

Step 3
Tracker

Step 4
Admin

Extra
Download & More

Closing
What’s Next?

PRELUDE
OVERVIEW & ASSUMPTIONS

Before we go into the code, let us start with an overview of the entire system so that you don’t get lost. Also, some of my assumptions so that you know what to expect from this guide.

SYSTEM OVERVIEW

There are a lot of ways to use a GPS tracking system, and this guide will go through one of the most common ways to use it – Tracking various delivery riders. Not because we want to be control freaks, but to let customers know where their orders are at, and to properly compensate the riders for their mileage. There are 4 parts to this system:

  • Database – To hold the last known locations of the riders.
  • Tracker – An app installed on the riders’ smartphone, or a website that they can visit. This one will send their GPS coordinates to the server.
  • Endpoint – Server-side PHP scripts to receive the coordinates, put them into the database, and to retrieve them from the database.
  • Admin – A page to show the current locations of the riders.

ASSUMPTIONS

Some of you guys should already have an existing project, so we will not reinvent another user system nor admin panel here. This guide will be purely touching on GPS tracking only. Also, this will be a barebones system to show you what is possible with web technology – No free lunches will be given to people who are working on paid projects. 😆 

I shall also assume that most of you guys are already good enough code ninjas, comfortable with PHP, HTML, CSS, Javascript, AJAX, JSON, and all the concepts. We will not go into the tiny boring little details such as “what is GPS” in this guide.

STEP 1
THE DATABASE

Now that we are done with the overview of the system, let us start building the system by laying the foundation – The database.

LAST KNOWN LOCATION

sql/track.sql
CREATE TABLE `gps_track` (
  `rider_id` int(11) 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=latin1;

ALTER TABLE `gps_track`
  ADD PRIMARY KEY (`rider_id`),
  ADD KEY `track_time` (`track_time`);
COMMIT;
FieldDescription
rider_idPrimary key, the rider ID. Could be the ID of whatever you want to track.
track_timeTime the rider last “checked in”.
track_lngLongitude.
track_latLatitude.

Yep, that is all we need, to store the last known locations of the riders.

RIDER TABLE

sql/riders.sql
CREATE TABLE `riders` (
  `rider_id` int(11) NOT NULL,
  `rider_name` varchar(255) NOT NULL,
  `rider_tel` varchar(64) NOT NULL,
  `rider_email` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `riders`
  ADD PRIMARY KEY (`rider_id`),
  ADD UNIQUE KEY `rider_email` (`rider_email`);

ALTER TABLE `riders`
  MODIFY `rider_id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT; 

This is not exactly used in the system. But the sake of completeness of this tutorial, here is an example rider database that one may have.

FieldDescription
rider_idPrimary key and auto-increment, The rider ID.
rider_nameThe rider’s name.
rider_telThe rider’s telephone number.
rider_emailThe rider’s email address.

STEP 2
ENDPOINT

Next, we will establish another piece of the foundations – The endpoint of the GPS tracking system which will receive and serve the GPS coordinates.

CONFIG FILE

lib/config.php

The very first script that we will create is the config file, a place for us to put all the settings into. Please remember to change the database settings to your own.

DATABASE LIBRARY

lib/lib-db.php
pdo = new PDO(
        $str, DB_USER, DB_PASSWORD, [
          PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
          PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
          PDO::ATTR_EMULATE_PREPARES => false
        ]
      );
    }

    // ERROR - CRITICAL STOP - THROW ERROR MESSAGE
    catch (Exception $ex) {
      print_r($ex);
      die();
    }
  }

  function __destruct () {
  // __destruct() : close connection when done

    if ($this->stmt !== null) { $this->stmt = null; }
    if ($this->pdo !== null) { $this->pdo = null; }
  }

  function exec ($sql, $data=null) {
  // exec() : run insert, replace, update, delete query
  // PARAM $sql : SQL query
  //       $data : array of data

    try {
      $this->stmt = $this->pdo->prepare($sql);
      $this->stmt->execute($data);
      $this->lastID = $this->pdo->lastInsertId();
    } catch (Exception $ex) {
      $this->error = $ex;
      return false;
    }
    $this->stmt = null;
    return true;
  }

  function start () {
  // start() : auto-commit off

    $this->pdo->beginTransaction();
  }

  function end ($commit=1) {
  // end() : commit or roll back?

    if ($commit) { $this->pdo->commit(); }
    else { $this->pdo->rollBack(); }
  }

  function fetchAll ($sql, $cond=null, $key=null, $value=null) {
  // fetchAll() : perform select query (multiple rows expected)
  // PARAM $sql : SQL query
  //       $cond : array of conditions
  //       $key : sort in this $key=>data order, optional
  //       $value : $key must be provided. If string provided, sort in $key=>$value order. If function provided, will be a custom sort.

    $result = [];
    try {
      $this->stmt = $this->pdo->prepare($sql);
      $this->stmt->execute($cond);
      // Sort in given order
      if (isset($key)) {
        if (isset($value)) {
          if (is_callable($value)) {
            while ($row = $this->stmt->fetch(PDO::FETCH_NAMED)) {
              $result[$row[$key]] = $value($row);
            }
          } else {
            while ($row = $this->stmt->fetch(PDO::FETCH_NAMED)) {
              $result[$row[$key]] = $row[$value];
            }
          }
        } else {
          while ($row = $this->stmt->fetch(PDO::FETCH_NAMED)) {
            $result[$row[$key]] = $row;
          }
        }
      }
      // No key-value sort order
      else {
        $result = $this->stmt->fetchAll();
      }
    } catch (Exception $ex) {
      $this->error = $ex;
      return false;
    }
    // Return result
    $this->stmt = null;
    return count($result)==0 ? false : $result ;
  }

  function fetch ($sql, $cond=null, $sort=null) {
  // fetch() : perform select query (single row expected)
  //           returns an array of column => value
  // PARAM $sql : SQL query
  //       $cond : array of conditions
  //       $sort : custom sort function

    $result = [];
    try {
      $this->stmt = $this->pdo->prepare($sql);
      $this->stmt->execute($cond);
      if (is_callable($sort)) {
        while ($row = $this->stmt->fetch(PDO::FETCH_NAMED)) {
          $result = $sort($row);
        }
      } else {
        while ($row = $this->stmt->fetch(PDO::FETCH_NAMED)) {
          $result = $row;
        }
      }
    } catch (Exception $ex) {
      $this->error = $ex;
      return false;
    }
    // Return result
    $this->stmt = null;
    return count($result)==0 ? false : $result ;
  }

  function fetchCol ($sql, $cond=null) {
  // fetchCol() : yet another version of fetch that returns a flat array
  // I.E. Good for one column SELECT `col` FROM `table`

    $this->stmt = $this->pdo->prepare($sql);
    $this->stmt->execute($cond);
    $result = $this->stmt->fetchAll(PDO::FETCH_COLUMN, 0);
    return count($result)==0 ? false : $result;
  }
}

Next, we have a database library that will do all the SQL heavy lifting work. This one is based on PDO, so it should work with a lot of others than just MySQL.

FunctionDescription
__constructThe constructor, automatically connects to the database when the object is created.
__destructThe destructor, automatically closes the database connection when the object is destroyed.
execRuns a single insert, replace, update, or delete query.
startAuto-commit off. Used for multiple queries and in conjunction with end.
endCommit or rollback. Used in conjunction with start.
fetchAllRun a select query. Returns an associative array of with multiple rows of results.
fetchRun a select query. Returns an associative array of column > value.
fetchColRun a select query that only picks on a single column. Returns a flat array of the specified column values.

GPS TRACKING LIBRARY

lib/lib-track.php
exec(
      "REPLACE INTO `gps_track` (`rider_id`, `track_time`, `track_lng`, `track_lat`) VALUES (?, ?, ?, ?)",
      [$id, date("Y-m-d H:i:s"), $lng, $lat]
    );
  }

  function get ($id) {
  // get() : get rider coordinates
  // PARAM $id : rider ID

    return $this->fetch(
      "SELECT * FROM `gps_track` WHERE `rider_id`=?",
      [$id]
    );
  }

  function getAll () {
  // getAll() : get all the rider locations
  // !! You might want to implement an "on active duty" flag in your own system
  // !! Just so that only the relevant riders are extracted

    return $this->fetchAll(
      "SELECT * FROM `gps_track`", null, "rider_id"
    );
  }
}

Yep, this simple library will store and retrieve the coordinates into the database.

FunctionDescription
updateUpdate the location of the given rider.
getGet the last known location of the given rider.
getAllGet all rider locations.

AJAX HANDLER (OR ENDPOINT)

ajax_track.php
 0,
      "message" => "Invalid request"
    ]);
    break;

  // UPDATE RIDER LOCATION
  case "update":
    $pass = $trackLib->update($_POST['rider_id'], $_POST['lng'], $_POST['lat']);
    echo json_encode([
      "status" => $pass ? 1 : 0,
      "message" => $pass ? "OK" : $trackLib->error
    ]);
    break;

  // GET RIDER LOCATION
  case "get":
    $location = $trackLib->get($_POST['rider_id']);
    echo json_encode([
      "status" => is_array($location) ? 1 : 0,
      "message" => $location
    ]);
    break;

  // GET ALL RIDER LOCATIONS
  case "getAll":
    $location = $trackLib->getAll();
    echo json_encode([
      "status" => is_array($location) ? 1 : 0,
      "message" => $location
    ]);
    break;
}

Lastly, here is the actual endpoint, which simply uses the libraries that we have previous created. How it works is very simple. We only need to pass in a $_POST['req'] to specify what we need, followed by the required parameters.

RequestDescription
update

Update the location of the given rider. Parameters:

  • rider_id
  • lng
  • lat
get

Get the last known location of a given rider. Parameters:

  • rider_id
getAll

Get all the last known locations of the riders.

STEP 3
TRACKER

Now that we have all the foundations ready, we have to build a simple tracker that will update the server of the rider’s current locations.

THE TRACKER SCRIPT

track.html


  
    
      Javascript Geolocation Tracking Demo
    

This is a demo tracking page. You will normally create a rider login page, or convert this into a webapp. For those who do not know - Check out Phonegap and Ionic.

Yep, that is the gist of it. All we have to do is to use the Javascript geolocation API to get the GPS coordinates and update the server accordingly. Of course, in your own real-life project, you will want to have a proper login system and identify your riders. Either that or you always have the option to create an Android/iOS app.

STEP 4
ADMIN

The final piece of the puzzle is to have an admin page that will extract the locations of the riders and show them on a map.

THE CENTRAL CONTROL

admin.html


  
    
      PHP Javascript Tracking Demo
    

So where the heck did the map go? Unfortunately, Google Maps API is no longer free and you will have to sign up to use it – Check out their official page.

EXTRA
DOWNLOAD & MORE

That’s all for the code, and here is the download link as promised – Plus a few small extras that may be useful to you.

LIMITATIONS & REAL-TIME TRACKING?

Hey, this is not a real-time system! Of course, it is not. While it is possible to do so, we have to consider the technical limitations and is it worth to do it. Firstly, that will drain out the smartphone batteries fast. Secondly, you will need a powerful network infrastructure to support a lot of “always on” socket connections. Lastly, a very robust server system that is capable of crunching real-time data.

So aye… If someone is willing to shell out that kind of money and think that it is beneficial for their business… Then why not?
 

SOURCE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
 

CLOSING
WHAT’S NEXT?

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you in your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

The post How to Create a GPS Tracking System With PHP and Javascript appeared first on Code Boxx.



This post first appeared on Xxxxxxxxx, please read the originial post: here

Share the post

How to Create a GPS Tracking System With PHP and Javascript

×

Subscribe to Xxxxxxxxx

Get updates delivered right to your inbox!

Thank you for your subscription

×