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

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay