DEV Community

Cover image for 🚚Memprediksi Geofence di Depan dengan Turf.js: Solusi Cerdas untuk Jalur Hauling
Ferry Ananda Febian
Ferry Ananda Febian

Posted on

3 2 2 2 2

🚚Memprediksi Geofence di Depan dengan Turf.js: Solusi Cerdas untuk Jalur Hauling

Sebagai pengelola armada truk di jalur hauling, memprediksi geofence berikutnya yang akan dilalui truk merupakan aspek penting untuk meningkatkan efisiensi dan keselamatan operasional. Dalam artikel ini, saya dan Yanuar Fabien sebagai Full Stack Developer di Minergo Systems akan membahas bagaimana kami menggunakan Turf.js untuk memproses data geofence dan memprediksi posisi truk di masa mendatang.

Dataset Geofence

Kami menggunakan data geofence dari aplikasi Traccar yang disimpan dalam file JSON dengan struktur berikut:

[
  {
    "id": 721,
    "name": "KM 40.50",
    "description": "",
    "area": "POLYGON ((-3.4584044876220554 115.56593021329513, -3.458300013067892 115.56610383129104, -3.459775990104413 115.56709532436714, -3.4598962627271885 115.56697279843891, -3.4584044876220554 115.56593021329513))",
    "attributes": "{\"StreetType\":\"KM Hauling\",\"GroupName\":\"Jalur Hauling\"}",
    "calendarid": null,
    "geotype": "Rambu",
    "group_name": null
  }
]
Enter fullscreen mode Exit fullscreen mode

Proses Format Geofence dengan Turf.js

Langkah pertama adalah memformat data geofence agar dapat diproses dengan Turf.js. Berikut adalah kode yang kami gunakan:

const fs = require("fs").promises;
const turf = require("@turf/turf");

async function formatGeofencesToTurf() {
  const geofences = await fs.readFile("public/geofences/TCGeofences.json", "utf-8").then((data) => {
    return JSON.parse(data).filter((geofence) => geofence.area.includes("POLYGON"));
  });

  const formattedGeofences = [];

  for (const geofence of geofences) {
    try {
      const coordinatesString = geofence.area.replace("POLYGON ((", "").replace(")", "").replaceAll(", ", ",");
      let coordinates = coordinatesString.split(",").map((point) => {
        const [lat, lng] = point.split(" ").map(Number);
        return [lng, lat];
      });
      if (coordinates[0] !== coordinates[coordinates.length - 1]) {
        coordinates.push(coordinates[0]);
      }

      formattedGeofences.push({
        name: geofence.name,
        coordinates,
        attributes: JSON.parse(geofence.attributes),
      });
    } catch (error) {
      console.warn(`Error in geofence ${geofence.name}: ${error.message}`);
    }
  }

  return formattedGeofences;
}
Enter fullscreen mode Exit fullscreen mode

Memprediksi Geofence Berikutnya

Fungsi prediksi didasarkan pada kecepatan truk dan arah pergerakannya. Kami menghitung titik tujuan (next point) dengan memanfaatkan fungsi Turf.js turf.destination. Berikut adalah kode prediksinya:

function getNextGeofence(unit, geofences, seconds) {
  const { latitude, longitude, course, attributes } = unit;
  const speed = JSON.parse(attributes || "{}")?.io24 || 0;
  const distance = (speed * seconds) / 3600; // Jarak dalam kilometer

  const currentPoint = turf.point([longitude, latitude]);
  const nextPoint = turf.destination(currentPoint, distance, course, { units: "kilometers" });

  for (const geofence of geofences) {
    try {
      const polygon = turf.polygon([geofence.coordinates]);
      if (turf.booleanPointInPolygon(nextPoint, polygon)) {
        return geofence;
      }
    } catch (error) {}
  }

  return null;
}
Enter fullscreen mode Exit fullscreen mode

Penjelasan Fungsi

  1. formatGeofencesToTurf:

    • Memformat data geofence dari file JSON menjadi bentuk array koordinat yang dapat digunakan oleh Turf.js.
  2. getNextGeofence:

    • Menghitung lokasi berikutnya truk berdasarkan kecepatan (dalam km/jam) dan arah pergerakan (dalam derajat).
    • Memanfaatkan fungsi turf.destination untuk menentukan titik tujuan dari lokasi saat ini.
    • Mengecek apakah titik tujuan berada dalam geofence tertentu menggunakan turf.booleanPointInPolygon.

Contoh Penggunaan

(async () => {
  const geofences = await formatGeofencesToTurf();

  const currentUnit = {
    latitude: -3.459,
    longitude: 115.566,
    course: 90, // arah dalam derajat (east)
    attributes: JSON.stringify({ io24: 40 }), // kecepatan dalam km/jam
  };

  const nextGeofence = getNextGeofence(currentUnit, geofences, 60); // Prediksi untuk 60 detik ke depan

  if (nextGeofence) {
    console.log(`Truk akan memasuki geofence berikutnya: ${nextGeofence.name}`);
  } else {
    console.log("Tidak ada geofence di depan dalam waktu 60 detik.");
  }
})();
Enter fullscreen mode Exit fullscreen mode

Kesimpulan

Dengan pendekatan ini, kami dapat memprediksi geofence berikutnya yang akan dilalui oleh truk berdasarkan data posisi, arah, dan kecepatan. Modul Turf.js memberikan fleksibilitas tinggi dalam menangani data geografis, memungkinkan kami mengembangkan fitur ini dengan efisien dan akurat.

Jangan lupa mampir di artikel sebelumnya, saya juga menggunakan Turf.js untuk menentukan posisi geofence sebuah truk dengan memanfaatkan koordinat GPS.
Menentukan Koordinat Berada di Geofence Tertentu dengan Turf.js

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more