function fetchTimeline() {
clearMap();
const deviceId = document.getElementById("deviceSelect").value;
const date = document.getElementById("dateSelect").value;
if (!deviceId || !date) {
alert("⚠️ يرجى اختيار جهاز وتاريخ.");
return;
}
const url = `http://localhost/gps_tracker/get_google_timeline.php?device_id=${deviceId}&date=${date}`;
fetch(url)
.then(response => response.json())
.then(async data => {
console.log("📅 بيانات المخطط الزمني:", data);
const timelineContainer = document.getElementById("timelineEntries");
timelineContainer.innerHTML = "";
if (data.error) {
alert(data.error);
return;
}
if (Array.isArray(data) && data.length > 0) {
// جمع الإحداثيات الصحيحة لجلب أسماء الأماكن دفعة واحدة
const coords = data
.map(loc => ({
lat: parseFloat(loc.latitude),
lng: parseFloat(loc.longitude)
}))
.filter(c => !isNaN(c.lat) && !isNaN(c.lng));
let placesMap = {};
try {
if (coords.length > 0) {
const res = await fetch('get_places_names.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ locations: coords })
});
if (res.ok) {
const placeData = await res.json();
if (placeData && placeData.status === 'success' && placeData.places) {
placesMap = placeData.places; // مفاتيح بصيغة "lat,lng" بدقة 6 خانات
}
}
}
} catch (e) {
console.warn('⚠️ تعذّر جلب أسماء الأماكن، سيتم العرض بالإحداثيات فقط:', e);
}
// إنشاء العلامات وبناء المخطط الزمني مع أسماء الأماكن
data.forEach(location => {
const lat = parseFloat(location.latitude);
const lng = parseFloat(location.longitude);
const timestamp = location.timestamp;
const deviceName = location.device_name;
if (!isNaN(lat) && !isNaN(lng)) {
const key = `${lat.toFixed(6)},${lng.toFixed(6)}`;
const placeName = placesMap[key] || `${lat.toFixed(6)}, ${lng.toFixed(6)}`;
const marker = L.marker([lat, lng])
.addTo(map)
.bindPopup(
`📍 الحي/المدينة/المنطقة: ${placeName}
` +
`📝 الجهاز: ${deviceName}
` +
`⏰ الوقت: ${timestamp}`
);
markers.push(marker);
const entry = document.createElement("div");
entry.classList.add("timeline-entry");
entry.innerHTML = `
${timestamp}
- 📍 الحي/المدينة/المنطقة: ${placeName}
— الجهاز: ${deviceName}
`;
entry.addEventListener("click", function() {
map.setView([lat, lng], 15);
marker.openPopup();
});
timelineContainer.appendChild(entry);
}
});
} else {
alert("❌ لا توجد بيانات متاحة لهذا الجهاز في التاريخ المحدد.");
}
})
.catch(error => console.error("⚠️ خطأ في جلب البيانات:", error));
}