BysMax
Back to course

Traccar API: Basics to Get Started

Discover the Traccar API, an open-source GPS tracking tool that offers powerful filtering capabilities to improve location data accuracy and system efficiency.

Emmanuel Díaz Leal Hernández

May 25, 2024
Intermediate

Authentication Setup

Traccar allows basic authentication (username and password) or via token. Use the Authorization header.

const username = "YOUR_USERNAME";
const password = "YOUR_PASSWORD";
const headers = {
  "Content-Type": "application/json",
  "Authorization": `Basic ${btoa(username + ":" + password)}`, // Base64 encoding
};

Get All Devices

To list all devices, make a GET request:

fetch("https://YOUR_TRACCAR_URL/api/devices", { headers })
  .then(response => response.json())
  .then(data => console.log("Devices:", data))
  .catch(error => console.error("Error:", error));

Create a Device

Add a device using POST:

fetch("https://YOUR_TRACCAR_URL/api/devices", {
  method: "POST",
  headers,
  body: JSON.stringify({
    name: "New Device",
    uniqueId: "DEVICE_UNIQUE_ID",
    status: "online",
    // Other optional parameters
  }),
})
  .then(response => response.json())
  .then(data => console.log("Created Device:", data))
  .catch(error => console.error("Error:", error));

Get Position Data

To get the last position of a specific device:

fetch("https://YOUR_TRACCAR_URL/api/positions", {
  headers,
})
  .then(response => response.json())
  .then(data => console.log("Positions:", data))
  .catch(error => console.error("Error:", error));

Update Device Information

You can update device details with PUT:

fetch("https://YOUR_TRACCAR_URL/api/devices/DEVICE_ID", {
  method: "PUT",
  headers,
  body: JSON.stringify({ name: "Updated Device Name" }),
})
  .then(response => response.json())
  .then(data => console.log("Updated Device:", data))
  .catch(error => console.error("Error:", error));

Delete a Device

To delete a device by its ID:

fetch("https://YOUR_TRACCAR_URL/api/devices/DEVICE_ID", {
  method: "DELETE",
  headers,
})
  .then(() => console.log("Device deleted"))
  .catch(error => console.error("Error:", error));

Create a Geofence

To add a new geofence:

fetch("https://YOUR_TRACCAR_URL/api/geofences", {
  method: "POST",
  headers,
  body: JSON.stringify({
    name: "Home Zone",
    area: "CIRCLE (latitude longitude, radius)", // Specify geofence area
  }),
})
  .then(response => response.json())
  .then(data => console.log("Created Geofence:", data))
  .catch(error => console.error("Error:", error));

Notifications, Events, and Other Features

If you need more information about the API, check the official Traccar API documentation or ask at the support forum. This is just a small part of what you can do with Traccar. If you need a basic guide or something more advanced, visit the Traccar documentation.

Comentarios (0)