limit osrm request

This commit is contained in:
Pringgosutono
2025-09-24 13:20:46 +07:00
parent a3f42315e4
commit 77e5b345b7

View File

@ -164,11 +164,16 @@
// },
// }).addTo(map)
function fetchOsrm(points) {
// balik koordinat: [lat, lon] -> [lon, lat]
const coords = points
function chunkArray(arr, size) {
const result = [];
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
}
// hints: N-1 semicolon
function fetchOsrm(points) {
const coords = points;
const hints = ";".repeat(points.length - 1);
const body = {
@ -191,14 +196,12 @@
return axios.request(config)
.then((response) => {
// console.log(JSON.stringify(response.data));
return response.data; // supaya bisa dipakai di luar
return response.data;
})
.catch((error) => {
console.error("Error:", err.message);
console.error("Error:", error.message);
return null;
});
}
function decodeOSRMGeometry(encoded) {
@ -233,23 +236,39 @@
return coordinates;
}
async function getCoordinates(points) {
const chunkSize = 500;
const chunks = chunkArray(points, chunkSize); // Split the points array into chunks of 500
let allCoords = [];
fetchOsrm(points).then(osrm => {
if (!osrm) return console.log("OSRM gagal");
for (const chunk of chunks) {
const osrm = await fetchOsrm(chunk); // Fetch OSRM data for each chunk
coords = osrm.routes[0].legs.flatMap(leg =>
if (!osrm) {
console.log("OSRM failed for chunk");
return;
}
const coords = osrm.routes[0].legs.flatMap(leg =>
leg.steps.flatMap(step =>
decodeOSRMGeometry(step.geometry)
)
);
L.polyline(coords, {
allCoords = allCoords.concat(coords); // Combine the result
}
// Now add the polyline to the map
L.polyline(allCoords, {
color: "#2980B9",
weight: 3,
opacity: 0.8
}).addTo(map);
// map.fitBounds(coords.map(c => L.latLng(c[0], c[1])));
});
// map.fitBounds(allCoords.map(c => L.latLng(c[0], c[1])));
}
// Usage: Pass the array of coordinates to the function
getCoordinates(points);
// start and finish point