Difference between revisions of "Manual:GPS-tracking"

From MikroTik Wiki
Jump to: navigation, search
Line 7: Line 7:
== Requirements ==
== Requirements ==
* Webserver of your choice
* Webserver of your choice, this example has the server running on port 8080
* SQLite3 module for PHP  
* SQLite3 module for PHP  
Line 103: Line 103:
== Result ==

Revision as of 14:45, 22 February 2018

The following article explains how to create a simple vehicle tracking system using the RouterOS GPS function and scripting.


This approach uses the recently introduced HTTP POST capability of RouterOS Fetch tool. It allows you to POST any kind of data to a webserver, right from RouterOS command line. Of course, you can use scripting, to fill the POST data with variables. The posted data will be written to an SQLITE3 database (file is created, if it doesn't exist) and then, read from the database and fead into a Leaflet.js PolyLine array. This is a proof of concept example, there is no authentication, security or error handling.


  • Webserver of your choice, this example has the server running on port 8080
  • PHP
  • SQLite3 module for PHP
  • RouterOS device with a working GPS module
  • RouterOS v6.40rc30 or above

Currently RouterOS only outputs DMS format coordinates, this makes the required PHP code substantially larger, because conversion of coordinate systems is required. Once DD coordinate format will be suppported in RouterOS, the code becomes even simpler.

RouterOS script

You can run this script in the Scheduler tool, to have your coordinates sent every n minutes.

       :global lat
       :global lon
       /system gps monitor once do={
       :set $lat $("latitude")
       :set $lon $("longitude")
       tool fetch mode=http url="" port=8080 http-method=post http-data=("{\"lat\":\"" . $lat . "\",\"lon\":\"" . $lon . "\"}") http-content-type="application/json"
       :put ("{\"lat\":\"" . $lat . "\",\"lon\":\"" . $lon . "\"}")

index.php file


Note: Create an empty directory called *sqlite_db* next to the index.php file.


// Converting DMS ( Degrees / minutes / seconds ) to decimal format
function DMStoDD($deg,$min,$sec)
	return $deg+((($min*60)+($sec))/3600);

// make sure this directory exists and is writeable. file will be created automatically upon first fetch
$loc = dirname(__FILE__).'/sqlite_db/coord.db';
$raw = file_get_contents('php://input');
$data = json_decode($raw);
if (!empty($data) && is_object($data) && property_exists($data,'lat') && property_exists($data,'lon')){
    if(file_exists($loc)) echo 'exists!'.chr(0xa);
    $src = 'SELECT name FROM sqlite_master WHERE type=\'table\' AND name=\'coordinates\'';
    $res = $db->querySingle($src);
    if (count($res)==0){
            $db->exec('CREATE TABLE coordinates (latitude TEXT, longitude TEXT, time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, added TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ');
	$lat = $lon = '';

	// the below section splits DMS coordinates apart and converts them to DD format via above function
	if(preg_match('/^(N|E|W|S)\ (\d+)\ (\d+)\'\ (\d+\.\d+)/',$data->lat,$result)){
		$lat = DMStoDD( $result[2], $result[3], $result[4]);
	if(preg_match('/^(N|E|W|S)\ (\d+)\ (\d+)\'\ (\d+\.\d+)/',$data->lon,$result)){
		$lon = DMStoDD( $result[2], $result[3], $result[4]);
	$ins = 'INSERT INTO coordinates (latitude,longitude) VALUES (\''.SQLite3::escapeString($lat).'\',\''.SQLite3::escapeString($lon).'\')';
	echo 'added!'.chr(0xa);

<!DOCTYPE html>
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin=""/>
  <script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet.js" integrity="sha512-/Nsx9X4HebavoBvEBuyp3I7od5tA0UzAxs+j83KgC8PU0kgB4XiK4Lfe4y4cgBtaRJQEIFCW+oC506aPT2L1zw==" crossorigin=""></script>
<div id="map" style="width: 800px; height: 600px;"></div>
var map = L.map('map').setView([0,0], 4);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
		attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    $result = $db->query('SELECT latitude,longitude FROM coordinates') or die($db->errorInfo()[2]);;  
    echo ' var latlngs = [ ';
    while($obj = $result->fetchArray()){
    	echo ' [ ' . $obj['latitude']. ' , '. $obj['longitude'] .' ], ';
    echo ' ]; ';
var polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);