Skip to content

GPS

The GPS (Global Positioning System) feature in RouterOS enables MikroTik devices to determine their precise geographic location using GPS receivers. This capability is essential for mobile networking applications, fleet management, location-aware routing, and time synchronization. GPS support is available on compatible MikroTik devices including the LtAP series, hAP ac3, and other devices with integrated or external GPS modules.

RouterOS GPS implementation supports the NMEA 0183 protocol and Simple Text Output Protocol, allowing compatibility with a wide range of GPS receivers. The system provides real-time position data including latitude, longitude, altitude, speed, and bearing information. Additionally, GPS can be configured to automatically set the router’s system time based on satellite time signals, providing accurate time synchronization without external NTP servers.

The GPS menu is located at /system gps in RouterOS and requires the gps package to be installed. Configuration involves enabling the GPS module, selecting the appropriate serial or USB port, and optionally configuring antenna selection for devices with both internal and external antenna options.

MikroTik offers several devices with built-in GPS capabilities designed for mobile and remote deployment scenarios. Understanding the specific features of each device helps in selecting the appropriate hardware for your GPS-dependent application.

The LtAP (Lite Access Point) family represents MikroTik’s primary mobile networking solution with integrated GPS. The LtAP mini features a low-gain internal GPS antenna suitable for vehicles with good sky visibility, while the LtAP and LtAP ac models support both internal and external antenna connections for improved signal reception in challenging environments. The hAP ac3 and hAP ac3 LTE6 kit models include integrated GPS modules, making them versatile choices for combined routing and location tracking applications.

Devices without built-in GPS can be enhanced with external USB GPS receivers that support NMEA 0183 output. These USB dongles connect via the router’s USB ports and are configured through the same /system gps menu. When using external GPS receivers, ensure compatibility with the NMEA 0183 standard and verify the required baud rate in the receiver’s documentation.

GPS configuration in RouterOS involves setting up the physical connection, enabling the GPS module, and adjusting parameters to match your specific hardware setup. The following sections detail the configuration process from port setup through advanced options.

Before enabling GPS, you must ensure the serial or USB port is available and properly configured. Only one application can use a serial port at a time, so verify that the port is not already in use by the serial console or other services.

/port print

This command displays all available ports and their current usage status. If the port you intend to use shows as “used-by” another service, you must release it before configuring GPS. The serial console commonly occupies serial ports on devices without USB options.

/system console print
/system console disable 0

The console disable command releases the serial port from console usage. On devices with multiple serial ports or USB ports, you may have more flexibility in port selection without requiring console changes.

Configure the port baud rate to match your GPS receiver specifications. Most NMEA 0183 GPS modules operate at 4800 baud, though some newer modules require 9600 baud or higher.

/port set usb1 baud-rate=4800 data-bits=8 parity=odd stop-bits=1 flow-control=none

For LtAP mini devices, the port should typically remain at auto-detect settings as the device handles initialization automatically.

With the port configured, enable and configure GPS through the system GPS menu.

/system gps set enabled=yes port=usb1
/system gps print

This basic configuration enables GPS on the specified USB port. Additional parameters allow fine-tuning the GPS behavior to match your requirements.

The channel parameter specifies which port channel the GPS device uses, with a default of 0 suitable for most single-channel GPS receivers. The init-channel and init-string parameters allow sending custom AT initialization commands to GPS modules that require specific configuration, such as Huawei cards that need continuous monitoring commands.

The gps-antenna-select parameter, available on devices with both internal and external antenna options, switches between antenna sources. The internal setting uses the built-in antenna, while external selects a connected external antenna for improved signal reception.

/system gps set gps-antenna-select=external

The set-system-time parameter, when enabled, automatically sets the router’s date and time based on GPS satellite time. This feature provides accurate time synchronization useful for timestamping log entries and events without relying on external NTP servers.

/system gps set set-system-time=yes

The coordinate-format parameter controls how latitude and longitude values are displayed. The dd format presents coordinates in decimal degrees (such as 56.969689), suitable for mathematical calculations and most mapping applications. The dms format displays degrees, minutes, and seconds (such as 56°58’10.88”N), which is more human-readable in navigation contexts. The ddmm format uses NMEA-style notation with degrees and decimal minutes.

/system gps set coordinate-format=dd

The LtAP series has specific port requirements for GPS operation. The internal GPS module on LtAP devices connects to the serial1 port rather than USB ports.

/port set serial1 baud-rate=115200
/system gps set port=serial1 channel=0 enabled=yes

The higher baud rate of 115200 is required for the LtAP’s internal GPS module to operate correctly. This configuration differs from external USB GPS receivers that typically use 4800 baud.

RouterOS provides comprehensive GPS monitoring capabilities through the monitor command, displaying real-time position data, satellite information, and signal quality metrics. Regular monitoring helps verify proper GPS operation and diagnose reception issues.

The primary monitoring command displays current GPS data:

/system gps monitor

The output includes critical position and quality information. The latitude and longitude fields provide the current coordinates in the configured coordinate format. The altitude field shows height above sea level in meters. The speed field indicates the current movement velocity in kilometers per hour, while true-bearing and magnetic-bearing provide directional information.

The valid field indicates whether the GPS has acquired a valid position fix. A value of “yes” confirms the GPS has sufficient satellite visibility to calculate position, while “none” indicates insufficient satellites or other acquisition issues.

Satellite-related metrics help assess signal quality. The satellites field shows the number of satellites the receiver is actively tracking. The fix-quality field indicates the quality of the position fix, with higher values indicating better accuracy. The horizontal-dilution (HDOP) field shows position accuracy degradation, with lower values indicating better precision.

date-and-time: sep/07/2021 08:26:26
latitude: 56.969689
longitude: 24.162471
altitude: 25.799999m
speed: 0.759320 km/h
destination-bearing: none
true-bearing: 185.500000 deg. True
magnetic-bearing: 0.000000 deg. Mag
satellites: 6
fix-quality: 1
horizontal-dilution: 1.3

The data-age parameter, introduced in RouterOS 7.1rc3, displays the time in seconds since the last NMEA message was received. This metric helps identify communication issues between the router and GPS receiver.

For applications requiring continuous GPS data, the monitor command can run continuously:

/system gps monitor once do={
:put ("Latitude: $"latitude)
:put ("Longitude: $"longitude)
}

This approach captures GPS data within scripts for automated processing and logging.

GPS reception issues can stem from hardware problems, configuration errors, or environmental factors affecting satellite visibility. Systematic troubleshooting identifies and resolves these issues.

Some GPS modules require specific baud rate settings to be recognized by RouterOS. If the GPS does not appear to be communicating, try adjusting the baud rate in the port menu:

/port set usb1 baud-rate=4800
/port set usb1 baud-rate=9600

Test different baud rates based on your GPS module’s specifications. NMEA 0183 devices commonly use 4800 baud, but newer modules may require higher speeds.

Devices with both internal and external antenna options may experience poor reception with the default internal antenna. The LtAP mini particularly benefits from external antenna installation for improved signal:

/system gps set gps-antenna-select=external

MikroTik offers the ACGPSA external GPS antenna designed for use with LtAP devices. This antenna provides significantly better reception than the built-in antenna, especially in vehicles with tinted windows or metal roofs.

Poor satellite reception results in invalid position data or low satellite counts. Solutions include relocating the device to a position with clearer sky visibility, ensuring the GPS antenna is properly positioned, and verifying the antenna connection is secure.

For vehicles, mounting the device near windows or using an external antenna typically improves reception. In stationary installations, ensure the antenna has a clear view of the sky without obstructions.

Some Huawei cellular modems include GPS functionality that requires specific initialization commands for continuous monitoring. The following init string enables continuous GPS monitoring on compatible Huawei cards:

/system gps set init-string="AT^WPDST=1,AT^WPDGP" port=usb1 enabled=yes

This sends the required AT commands to activate GPS data output on Huawei’s proprietary protocol.

RouterOS GPS functionality enables sophisticated tracking applications by combining GPS data with scripting and network tools. Two primary methods exist for transmitting GPS data to remote servers: HTTP POST and MQTT protocols.

The HTTP POST method uses RouterOS fetch tool to send GPS coordinates to a web server. This approach requires a server-side component to receive and store the data, typically using PHP and SQLite.

The following script captures GPS coordinates and sends them to a web server via HTTPS POST:

{
:global lat
:global lon
/system gps monitor once do={
:set $lat $("latitude")
:set $lon $("longitude")
}
tool fetch mode=https url="https://YOURSERVER.com/index.php" port=443 http-method=post http-data=("{\"lat\":\"" . $lat . "\",\"lon\":\"" . $lon . "\"}") http-header-field="Content-Type: application/json"
:put ("{\"lat\":\"" . $lat . "\",\"lon\":\"" . $lon . "\"}")
}

Schedule this script to run at your desired interval using the scheduler:

/system scheduler add name=gps-tracking interval=1s on-event="/system/script run gps-tracking"

A 1-second interval provides frequent position updates suitable for real-time tracking applications.

Server-side PHP code receives the POST data and stores coordinates in an SQLite database:

<?php
$loc = dirname(__FILE__).'/sqlite_db/coord.db';
$db = new SQLite3($loc,SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE);
$raw = file_get_contents('php://input');
$raw = preg_replace('/\\x00/','',$raw);
$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 ) ');
}
$regex = '/^(|\-)([0-9]{2,3}\.[0-9]{0,8})$/';
if (preg_match($regex,$data->lat) && preg_match($regex,$data->lon) )
{
$lat = $data->lat;
$lon = $data->lon;
}
$ins = 'INSERT INTO coordinates (latitude,longitude) VALUES (\''.SQLite3::escapeString($lat).'\',\''.SQLite3::escapeString($lon).'\')';
$db->exec($ins);
die();
}
?>

The received coordinates can be visualized on a map using Leaflet.js, with the PHP backend querying the database and generating the polyline array for display.

The MQTT protocol provides a more robust approach to GPS tracking, particularly suitable for integration with IoT platforms like ThingsBoard. This method uses the RouterOS IoT package and requires the gps and iot packages.

Configure the MQTT broker connection:

/iot/mqtt/brokers add name=tb address=x.x.x.x port=1883 username=access_token

For SSL-protected connections:

/iot/mqtt/brokers add name=tb address=x.x.x.x port=8883 username=access_token ssl=yes

Create a script to capture and publish GPS data:

/system/script/add dont-require-permissions=no name=mqttgps owner=admin policy="ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon" source=" ###Configuration###
:local broker \"tb\"
:local topic \"v1/devices/me/telemetry\"
###Variables###
:global lat
:global lon
:global alt1
:global alt2
###GPS###
/system gps monitor once do={
:set $lat $(\"latitude\");
:set $lon $(\"longitude\");
:set $alt1 $(\"altitude\")}
:set $alt2 [:pick $alt1 0 [find $alt1 \" m\"]]
###MQTT###
:local message \"{\\\"latitude\\\":$lat,\\\"longitude\\\":$lon,\\\"altitude\\\":$alt2}\"
:if ($lat != \"none\") do={
/iot mqtt publish broker=$broker topic=$topic message=$message} else={:log info \"Latitude=none, not posting anything!\"}"

Schedule the script for regular execution:

/system scheduler add name=mqttgps interval=30s on-event="/system/script run mqttgps"

ThingsBoard receives the telemetry data and can display it on interactive maps using the Maps widget bundle. The platform stores historical data, enabling tracking playback and route visualization.

Geofencing uses GPS coordinates to define geographic boundaries and trigger automated actions when a device enters or exits those boundaries. RouterOS implements geofencing through scripting, using the GPS monitor command to read position data and comparing coordinates against defined zone limits.

The simplest geofence uses a rectangular boundary defined by minimum and maximum latitude and longitude values. This approach suits most practical applications including delivery zone monitoring, fleet management, and equipment theft detection.

Define the zone boundaries and create a script that reads current position, evaluates it against the zone, and acts on boundary transitions:

/system/script/add name=geofence owner=admin policy="ftp,reboot,read,write,policy,test,password,sniff,sensitive,romon" source="
# Zone boundary definition
:local minLat 37.7740
:local maxLat 37.7760
:local minLon -122.4200
:local maxLon -122.4180
# Read current GPS position
:global lat
:global lon
/system gps monitor once do={
:set \$lat \$(\"latitude\")
:set \$lon \$(\"longitude\")
}
# Skip evaluation if GPS has no fix
:if (\$lat = \"none\") do={ :log warning \"Geofence: no GPS fix, skipping\"; :error \"no fix\" }
# Convert string values to numbers for comparison
:local latNum [:tonum \$lat]
:local lonNum [:tonum \$lon]
# Persist previous zone state across runs
:global inZone
# Determine current zone state
:local isInZone true
:if ((\$latNum < \$minLat) || (\$latNum > \$maxLat) || (\$lonNum < \$minLon) || (\$lonNum > \$maxLon)) do={
:set isInZone false
}
# Trigger only on state transitions
:if ((\$inZone = true) && (\$isInZone = false)) do={
:log warning \"GeoFence: device left zone\"
# Add notification or action here, e.g.: /tool e-mail send ...
}
:if ((\$inZone = false) && (\$isInZone = true)) do={
:log info \"GeoFence: device entered zone\"
}
:set inZone \$isInZone"

The script uses a :global inZone variable to persist the previous zone state between executions. By comparing the current state against the previous state, the script fires actions only on transitions (enter or exit), avoiding repeated alerts while the device remains in the same zone.

Run the geofence script periodically using the scheduler. The evaluation interval determines how quickly boundary crossings are detected:

/system/scheduler/add name=geofence-check interval=30s on-event="/system/script/run geofence"

A 30-second interval provides reasonable responsiveness while minimizing GPS receiver load. Adjust the interval based on the speed of movement and required detection latency — slower assets such as ships or stationary equipment can use longer intervals.

When a boundary crossing is detected, the script can execute any RouterOS action. Common responses include sending an email notification, publishing an MQTT message to an IoT platform, triggering an SMS via a connected LTE modem, or running another script that modifies firewall rules or routing.

To send an email alert on zone exit, replace the comment in the transition block with:

/tool e-mail send to="[email protected]" subject="GeoFence Alert" body="Device has left the defined zone."

To publish a geofence alert via MQTT (requires the iot package and a configured broker):

/iot mqtt publish broker=tb topic="v1/devices/me/telemetry" message="{\"geofence_status\":\"left_zone\"}"

Monitor multiple independent zones by defining additional min/max boundary sets and evaluating each in sequence. Use separate global variables to track each zone’s state independently:

# Zone A: warehouse
:local zoneAMinLat 37.7740
:local zoneAMaxLat 37.7760
:local zoneAMinLon -122.4200
:local zoneAMaxLon -122.4180
:global inZoneA
# Zone B: depot
:local zoneBMinLat 37.7800
:local zoneBMaxLat 37.7820
:local zoneBMinLon -122.4150
:local zoneBMaxLon -122.4130
:global inZoneB

Evaluate each zone’s boundaries separately, using its corresponding global state variable for transition detection.

RouterOS GPS supports the NMEA 0183 standard protocol used by most GPS receivers. Understanding this protocol helps in debugging and integrating with third-party systems.

NMEA 0183 sentences contain various data types including GGA (fix information), RMC (recommended minimum specific GPS data), and GSA (DOP and active satellites). RouterOS parses these sentences and exposes the relevant data through the monitoring commands.

The Simple Text Output Protocol provides an alternative output format that some GPS modules may use. This protocol typically outputs position data in a simpler format that may be easier to parse for custom applications.

GPS provides highly accurate time information derived from atomic clocks on GPS satellites. When set-system-time is enabled, RouterOS automatically synchronizes the system clock with GPS time.

This synchronization is particularly valuable in locations without reliable internet connectivity for NTP synchronization. The GPS time signal maintains accuracy independent of network infrastructure, making it suitable for isolated deployments and network edge devices.

Time synchronization occurs automatically when GPS achieves a valid fix. The date and time values from the GPS monitor output confirm successful synchronization.

PropertyValue
Packagegps
Menu Location/system gps
ProtocolsGPS, NMEA 0183, Simple Text Output Protocol
Coordinate Formatsdd (Decimal Degrees), dms (Degrees Minutes Seconds), ddmm
Typical Baud Rates4800, 9600, 115200
Altitude UnitMeters
Speed UnitKilometers per hour
  • CLI: Command Line Interface
  • dd: Decimal Degrees coordinate format
  • dms: Degrees Minutes Seconds coordinate format
  • GGA: NMEA Global Positioning System Fix Data
  • GPS: Global Positioning System
  • HDOP: Horizontal Dilution of Precision
  • HTTP: Hypertext Transfer Protocol
  • IoT: Internet of Things
  • LTE: Long Term Evolution
  • MQTT: Message Queuing Telemetry Transport
  • NMEA: National Marine Electronics Association
  • NTP: Network Time Protocol
  • PHP: PHP: Hypertext Preprocessor
  • RMC: NMEA Recommended Minimum Specific GPS Data
  • SQLite: Structured Query Language Database
  • SSL: Secure Sockets Layer
  • USB: Universal Serial Bus