File size: 4,437 Bytes
8de71e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
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: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> 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}<br>Longitude: ${lng}<br>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}<br>Longitude: ${longitude}`);
        }
    });
}

// Initialize map when the window loads
window.onload = initMap;