// KMZ Export functionality for FTTH Planner // Main export function function exportToKMZ() { showNotification('Menggenerate KMZ file...', 'info'); // Get all items and routes data Promise.all([ fetchAllItems(), fetchAllRoutes() ]).then(function(results) { let items = results[0]; let routes = results[1]; // Validate data if (!items || items.length === 0) { showNotification('Tidak ada data item untuk diekspor', 'warning'); return; } // Filter items with valid coordinates let validItems = items.filter(function(item) { let lat = parseFloat(item.latitude); let lng = parseFloat(item.longitude); return !isNaN(lat) && !isNaN(lng); }); if (validItems.length === 0) { showNotification('Tidak ada item dengan koordinat yang valid untuk diekspor', 'warning'); return; } if (validItems.length < items.length) { let skipped = items.length - validItems.length; showNotification(`${skipped} item dilewati karena koordinat tidak valid`, 'warning'); } // Generate KML content let kmlContent = generateKML(validItems, routes); // Create KMZ file and download createKMZFile(kmlContent); }).catch(function(error) { console.error('Error exporting KMZ:', error); showNotification('Error menggenerate KMZ: ' + error.message, 'error'); }); } // Fetch all items from API function fetchAllItems() { return new Promise(function(resolve, reject) { $.ajax({ url: 'api/items.php', method: 'GET', success: function(response) { if (response.success) { resolve(response.data); } else { reject(new Error(response.message || 'Failed to fetch items')); } }, error: function(xhr, status, error) { reject(new Error('API error: ' + error)); } }); }); } // Fetch all routes from API function fetchAllRoutes() { return new Promise(function(resolve, reject) { $.ajax({ url: 'api/routes.php', method: 'GET', success: function(response) { if (response.success) { resolve(response.data); } else { reject(new Error(response.message || 'Failed to fetch routes')); } }, error: function(xhr, status, error) { reject(new Error('API error: ' + error)); } }); }); } // Generate KML content function generateKML(items, routes) { let kml = ` FTTH Planner Export Export data infrastruktur FTTH dari FTTH Planner ${generateStyles()} ${generateItemPlacemarks(items)} ${generateRoutePlacemarks(routes)} `; return kml; } // Generate KML styles for different item types function generateStyles() { return ` `; } // Generate placemarks for items function generateItemPlacemarks(items) { let placemarks = ''; items.forEach(function(item) { // Validate coordinates let lat = parseFloat(item.latitude); let lng = parseFloat(item.longitude); if (isNaN(lat) || isNaN(lng)) { console.warn('Invalid coordinates for item:', item.name, 'lat:', item.latitude, 'lng:', item.longitude); return; // Skip this item } let styleId = getStyleId(item.item_type_name); let description = generateItemDescription(item); placemarks += ` ${escapeXML(item.name)} #${styleId} ${lng},${lat},0 `; }); return placemarks; } // Generate placemarks for routes function generateRoutePlacemarks(routes) { let placemarks = ''; routes.forEach(function(route) { if (route.route_coordinates) { let coordinates = ''; try { let coordArray = JSON.parse(route.route_coordinates); coordinates = coordArray.map(coord => `${coord.lng || coord[1]},${coord.lat || coord[0]},0`).join(' '); } catch (e) { console.warn('Invalid route coordinates for route', route.id); return; } let styleId = 'route-' + route.status; let description = generateRouteDescription(route); placemarks += ` Route: ${escapeXML(route.from_item_name)} → ${escapeXML(route.to_item_name)} #${styleId} 1 ${coordinates} `; } }); return placemarks; } // Get style ID based on item type function getStyleId(itemType) { switch(itemType) { case 'OLT': return 'olt-style'; case 'Tiang Tumpu': return 'tiang-style'; case 'ODP': return 'odp-style'; case 'ODC': return 'odc-style'; case 'Pelanggan': return 'pelanggan-style'; default: return 'odp-style'; } } // Generate item description HTML function generateItemDescription(item) { let description = ` `; if (item.description) { description += ``; } if (item.address) { description += ``; } // Handle coordinates safely let lat = parseFloat(item.latitude); let lng = parseFloat(item.longitude); let coordText = (isNaN(lat) || isNaN(lng)) ? 'Koordinat tidak valid' : `${lat.toFixed(6)}, ${lng.toFixed(6)}`; description += ``; if (item.tube_color_name) { description += ``; } if (item.core_used) { description += ``; } if (item.splitter_main_ratio) { description += ``; } if (item.splitter_odp_ratio) { description += ``; } description += ``; description += `
Jenis:${item.item_type_name}
Nama:${escapeXML(item.name)}
Deskripsi:${escapeXML(item.description)}
Alamat:${escapeXML(item.address)}
Koordinat:${coordText}
Warna Tube:${item.tube_color_name}
Core Digunakan:${item.core_used}
Splitter Utama:${item.splitter_main_ratio}
Splitter ODP:${item.splitter_odp_ratio}
Status:${getStatusText(item.status)}
`; return description; } // Generate route description HTML function generateRouteDescription(route) { let distance = route.distance ? (route.distance / 1000).toFixed(2) + ' km' : 'Unknown'; return `
Dari:${escapeXML(route.from_item_name || 'Unknown')}
Ke:${escapeXML(route.to_item_name || 'Unknown')}
Jarak:${distance}
Tipe Kabel:${escapeXML(route.cable_type || 'Fiber Optic')}
Jumlah Core:${route.core_count || 24}
Status:${getStatusText(route.status)}
`; } // Escape XML special characters function escapeXML(text) { if (!text) return ''; return text.toString() .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } // Get status text in Indonesian function getStatusText(status) { switch(status) { case 'active': return 'Aktif'; case 'inactive': return 'Tidak Aktif'; case 'maintenance': return 'Maintenance'; case 'planned': return 'Perencanaan'; case 'installed': return 'Terpasang'; default: return status || 'Unknown'; } } // Create KMZ file and trigger download function createKMZFile(kmlContent) { try { // Create ZIP file containing the KML let zip = new JSZip(); zip.file("doc.kml", kmlContent); // Generate KMZ file zip.generateAsync({type:"blob"}).then(function(content) { // Create filename with timestamp let timestamp = new Date().toISOString().slice(0,19).replace(/:/g,'-'); let filename = `FTTH_Planner_Export_${timestamp}.kmz`; // Save file saveAs(content, filename); showNotification(`KMZ file berhasil diunduh: ${filename}`, 'success'); }).catch(function(error) { console.error('Error creating KMZ:', error); showNotification('Error membuat file KMZ: ' + error.message, 'error'); }); } catch (error) { console.error('Error in createKMZFile:', error); showNotification('Error membuat KMZ file: ' + error.message, 'error'); } } // Add export button to global scope window.exportToKMZ = exportToKMZ;