const API_KEY = "94078593b1c2b2f226fb88d8ee037873da3844db"; let map; let csvData = null; // Initialize the map function initMap() { map = L.map('map').setView([20.5937, 78.9629], 5); // Centered on India L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© OpenStreetMap contributors' }).addTo(map); // Add click event listener to the map map.on('click', onMapClick); } // Function to handle the map click event async function onMapClick(e) { const { lat, lng } = e.latlng; try { const populationDensity = await fetchLULCStatistics(lat, lng); // Create popup L.popup() .setLatLng([lat, lng]) .setContent(`Latitude: ${lat}
Longitude: ${lng}
Population Density: ${populationDensity}`) .openOn(map); } catch (error) { console.error("Error fetching data:", error); } } // Function to fetch LULC Statistics from the Bhuvan API async function fetchLULCStatistics(latitude, longitude) { const apiUrl = `https://bhuvan-api.gov.in/lulc_statistics?lat=${latitude}&lon=${longitude}&token=${API_KEY}`; try { const response = await fetch(apiUrl); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); const populationDensity = data.population_density || "Data not available"; return populationDensity; } catch (error) { console.error("Failed to fetch LULC statistics:", error); return "Error fetching data"; } } // Drag and Drop Functionality const dropArea = document.getElementById('drop-area'); const csvUpload = document.getElementById('csv-upload'); ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => { dropArea.addEventListener(eventName, preventDefaults, false) }) function preventDefaults (e) { e.preventDefault() e.stopPropagation() } ['dragenter', 'dragover'].forEach(eventName => { dropArea.addEventListener(eventName, highlight, false) }) ['dragleave', 'drop'].forEach(eventName => { dropArea.addEventListener(eventName, unhighlight, false) }) function highlight(e) { dropArea.classList.add('highlight') } function unhighlight(e) { dropArea.classList.remove('highlight') } dropArea.addEventListener('drop', handleDrop, false) function handleDrop(e) { const dt = e.dataTransfer const files = dt.files handleFiles(files) } csvUpload.addEventListener('change', function() { handleFiles(this.files); }); function handleFiles(files) { const file = files[0]; if (file && file.type === "text/csv") { const reader = new FileReader(); reader.onload = function(event) { csvData = event.target.result; plotCsvDataOnMap(); }; reader.readAsText(file); } else { alert("Please upload a valid CSV file."); } } // CSV Parsing and Map Plotting function parseCSV(csvText) { const lines = csvText.trim().split('\n'); const headers = lines[0].split(',').map(header => header.trim()); const data = []; for (let i = 1; i < lines.length; i++) { const values = lines[i].split(',').map(value => value.trim()); if (values.length === headers.length) { const entry = {}; for (let j = 0; j < headers.length; j++) { entry[headers[j]] = values[j]; } data.push(entry); } } return data; } // Function to plot CSV data on the map function plotCsvDataOnMap() { if (!csvData) { alert("Please upload a CSV file first."); return; } const data = parseCSV(csvData); // Clear existing markers on the map (if any) map.eachLayer(function (layer) { if (layer instanceof L.Marker) { map.removeLayer(layer); } }); data.forEach(async entry => { if (entry.Latitude && entry.Longitude) { const latitude = parseFloat(entry.Latitude); const longitude = parseFloat(entry.Longitude); // Add marker for each location L.marker([latitude, longitude]).addTo(map) .bindPopup(`Latitude: ${latitude}
Longitude: ${longitude}`); } }); } // Initialize map when the window loads window.onload = initMap;