Debug School

rakesh kumar
rakesh kumar

Posted on

Implementing a Vehicle GPS Tracker in website

This guide covers how to set up a vehicle GPS tracking system from scratch—including when and how to add GPS tracker information to each vehicle—in a web solution with a React frontend (where you have vehicle CRUD) and a Laravel backend.

System Design Overview
Each vehicle in your system should have a unique ID.

GPS tracking devices (hardware or via a mobile app) send regular position updates (latitude/longitude and timestamp) to your backend.

Backend (Laravel) stores GPS data and exposes API endpoints for the frontend.

Frontend (React) fetches and displays live vehicle locations on a map.

Update Your Vehicle CRUD to Store Tracker Info
When adding/editing a vehicle, store its GPS tracker identifier (tracker serial, IMEI, or a unique token).

Laravel vehicle migration (add a tracker field):

Schema::table('vehicles', function (Blueprint $table) {
    $table->string('gps_tracker_id')->nullable(); // Add tracker ID
});
Enter fullscreen mode Exit fullscreen mode

Vehicle Model:

protected $fillable = [..., 'gps_tracker_id'];
React Frontend (Add/Edit Vehicle):

Add an input for "GPS Tracker ID" in your vehicle form.

Set Up Laravel: Store Incoming GPS Data
a) Make a migration for the positions:

php artisan make:model GpsPosition -m
Enter fullscreen mode Exit fullscreen mode

Edit the migration:

Schema::create('gps_positions', function (Blueprint $table) {
    $table->id();
    $table->unsignedBigInteger('vehicle_id');
    $table->decimal('latitude', 10, 7);
    $table->decimal('longitude', 10, 7);
    $table->timestamp('timestamp');
    $table->foreign('vehicle_id')->references('id')->on('vehicles')->onDelete('cascade');
    $table->timestamps();
});
Enter fullscreen mode Exit fullscreen mode

Run migrations:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

b) Make a controller for GPS data:

php artisan make:controller GpsController
Enter fullscreen mode Exit fullscreen mode

GpsController.php:

public function update(Request $request)
{
    $validated = $request->validate([
        'gps_tracker_id' => 'required|string|exists:vehicles,gps_tracker_id',
        'latitude' => 'required|numeric',
        'longitude' => 'required|numeric',
        'timestamp' => 'sometimes|date',
    ]);
    $vehicle = Vehicle::where('gps_tracker_id', $validated['gps_tracker_id'])->first();
    GpsPosition::create([
        'vehicle_id' => $vehicle->id,
        'latitude' => $validated['latitude'],
        'longitude' => $validated['longitude'],
        'timestamp' => $validated['timestamp'] ?? now(),
    ]);
    return response()->json(['status' => 'ok']);
}

public function latest()
{
    $positions = GpsPosition::query()
        ->select('vehicle_id', 'latitude', 'longitude', 'timestamp')
        ->orderByDesc('timestamp')
        ->get()
        ->unique('vehicle_id')
        ->values();
    return response()->json($positions);
}
Enter fullscreen mode Exit fullscreen mode

c) API Routes (routes/api.php):

Route::post('/gps-update', [GpsController::class, 'update']);
Route::get('/vehicle-locations', [GpsController::class, 'latest']);
Enter fullscreen mode Exit fullscreen mode

Sending GPS Data from Each Vehicle
Hardware GPS tracker: Configure it to send HTTP POSTs to /api/gps-update. Most commercial trackers allow setting a server URL and send their ID as gps_tracker_id in the request.

Via smartphone app: Build or use an existing app to post GPS data in the correct format.

Sample POST payload:

json
{
    "gps_tracker_id": "ABC123456",
    "latitude": 19.0760,
    "longitude": 72.8777,
    "timestamp": "2025-07-23T10:45:00Z"
}
Enter fullscreen mode Exit fullscreen mode

Sample cURL command for testing:

curl -X POST https://yourdomain.com/api/gps-update \
  -H "Content-Type: application/json" \
  -d '{"gps_tracker_id":"ABC123456","latitude":19.0760,"longitude":72.8777,"timestamp":"2025-07-23T10:45:00Z"}'
Enter fullscreen mode Exit fullscreen mode

Display Vehicle Locations in React
a) Fetch live locations from Laravel backend:

import axios from "axios";
import React, { useState, useEffect } from "react";

function VehicleMap() {
  const [locations, setLocations] = useState([]);
  useEffect(() => {
    const fetchLocations = () => {
      axios.get("/api/vehicle-locations")
        .then(res => setLocations(res.data));
    };
    fetchLocations();
    const interval = setInterval(fetchLocations, 5000);
    return () => clearInterval(interval);
  }, []);
  // Render map and markers with locations state
}
export default VehicleMap;
Enter fullscreen mode Exit fullscreen mode

b) Plot on a map (using react-leaflet):

import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
import "leaflet/dist/leaflet.css";

<MapContainer center={[19.0760, 72.8777]} zoom={10} style={{height: "400px", width: "100%"}}>
  <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
  {locations.map(vehicle =>
    <Marker key={vehicle.vehicle_id} position={[vehicle.latitude, vehicle.longitude]}>
      <Popup>
        Vehicle {vehicle.vehicle_id}<br/>
        {vehicle.latitude}, {vehicle.longitude}
      </Popup>
    </Marker>
  )}
</MapContainer>
Enter fullscreen mode Exit fullscreen mode

When to Add a GPS Tracker
At vehicle addition: When you create a vehicle entry in your CRUD, enter or scan the GPS tracker’s ID.

At installation: Install the GPS hardware or app in the vehicle. Configure the tracker to send data to your Laravel API with the correct gps_tracker_id.

For updating: Allow editing the GPS tracker ID if the physical tracker is ever replaced.

Security & Best Practices
Protect the /api/gps-update endpoint with an API key, token, or IP whitelist.

Use HTTPS for all API calls.

Validate all GPS data on the backend.

Only allow authenticated/authorized users to see live data in your React app.

How to add Vehicle GPS tracker to websites to track from websites and app using traccar step by step details

This guide details how to set up vehicle GPS tracking so your users can see live locations on your website and app, using a self-hosted Traccar server, a Laravel backend, and a React frontend.

  1. Set Up and Register Devices With Traccar A.
Install and Run Traccar
Enter fullscreen mode Exit fullscreen mode

Download and install Traccar from the official website.

Complete the setup; Traccar will run on port 8082 by default.

Access the web interface at http://your-server-ip:8082 and set an admin password.

B. Add Vehicle Trackers
Obtain each GPS tracker's unique ID/IMEI (see the device label, manual, or Traccar logs).

In the Traccar web UI, go to “Devices” and add a new device for every vehicle:

Name: Friendly name (e.g., “Truck 101”).

Identifier: Unique device ID/IMEI.

C. Configure Devices to Report to Traccar
Hardware trackers: Set the server IP/hostname and port (found on the Traccar devices list) as per your tracker’s manual.

Smartphone trackers: For Traccar Client app, set server to http://your-server-ip:8082 and a unique identifier.

  1. Set Up Laravel Backend as API Gateway A. Install Traccar Laravel Package
composer require mr-wolf-gb/traccar
Enter fullscreen mode Exit fullscreen mode

Publish config:

php artisan vendor:publish --provider="MrWolfGb\Traccar\TraccarServiceProvider"
Enter fullscreen mode Exit fullscreen mode

Configure Connection
Set Traccar details in your .env:

TRACCAR_BASE_URL="http://your-server-ip:8082/"
TRACCAR_USERNAME=your-traccar-admin
TRACCAR_PASSWORD=your-password
Enter fullscreen mode Exit fullscreen mode

C. Vehicles Table: Store Device IDs
Edit your vehicles table and model to add a column for traccar_device_id (which may be IMEI or uniqueId):

Schema::table('vehicles', function ($table) {
    $table->string('traccar_device_id')->nullable();
});
Enter fullscreen mode Exit fullscreen mode

Frontend/CMS forms should include a field for this ID.

D. Laravel API Endpoint to Fetch Locations
Create an endpoint (e.g., /api/vehicle-locations) that queries Traccar for latest positions:

use MrWolfGb\Traccar\Facades\Traccar;

public function getVehicleLocations()
{
    $vehicles = Vehicle::all()->keyBy('traccar_device_id');
    $positions = Traccar::positions();

    $vehicleMarkers = [];
    foreach ($positions as $pos) {
        $devId = $pos['deviceId'];
        $device = Traccar::device($devId);
        if ($device && isset($vehicles[$device['uniqueId']])) {
            $vehicle = $vehicles[$device['uniqueId']];
            $vehicleMarkers[] = [
                'vehicle_id' => $vehicle->id,
                'name' => $vehicle->name,
                'latitude' => $pos['latitude'],
                'longitude' => $pos['longitude'],
                'timestamp' => $pos['fixTime'],
            ];
        }
    }
    return response()->json($vehicleMarkers);
}
Enter fullscreen mode Exit fullscreen mode

Register this method as a route in api.php:

Route::get('/vehicle-locations', [VehicleController::class, 'getVehicleLocations']);
Enter fullscreen mode Exit fullscreen mode
  1. React Frontend: Live Map and Vehicle Tracking A. Fetch Vehicle Locations from Laravel Install Axios:
npm install axios
Enter fullscreen mode Exit fullscreen mode

Fetch data in React:

import axios from 'axios';
import React, { useEffect, useState } from 'react';

function VehicleMap() {
  const [vehicles, setVehicles] = useState([]);
  useEffect(() => {
    const fetchLocations = () => {
      axios.get('/api/vehicle-locations').then(res => setVehicles(res.data));
    };
    fetchLocations();
    const interval = setInterval(fetchLocations, 5000);
    return () => clearInterval(interval);
  }, []);
  // Render map here
}
Enter fullscreen mode Exit fullscreen mode

B. Display Vehicles on a Map
Install react-leaflet and leaflet:

npm install react-leaflet leaflet
Enter fullscreen mode Exit fullscreen mode

Add Leaflet CSS in your main JS file:

import 'leaflet/dist/leaflet.css';
Enter fullscreen mode Exit fullscreen mode

In your map component:

import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";

<MapContainer center={[19.0760, 72.8777]} zoom={10} style={{height: "400px", width: "100%"}}>
  <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
  {vehicles.map(vehicle => (
    <Marker key={vehicle.vehicle_id} position={[vehicle.latitude, vehicle.longitude]}>
      <Popup>
        {vehicle.name}<br/>
        {vehicle.latitude},{vehicle.longitude}<br/>
        {vehicle.timestamp}
      </Popup>
    </Marker>
  ))}
</MapContainer>
Enter fullscreen mode Exit fullscreen mode
  1. Security and Best Practices Secure your /api/vehicle-locations endpoint (JWT/session/user roles as needed).

Only expose Traccar ports/services required for your usage.

Use HTTPS for all data exchanges between tracker devices, backend, and frontend.

Store tracker IDs carefully and validate incoming data.

Top comments (0)