File size: 10,665 Bytes
3a84963
 
 
 
 
 
 
b96ab7a
3a84963
 
e383754
3a84963
 
 
 
 
e383754
 
 
 
 
 
 
 
b8778f9
3a84963
e383754
 
 
c99736d
 
3a84963
 
c99736d
e383754
c99736d
 
 
 
 
 
 
e383754
c99736d
 
 
 
 
e383754
c99736d
3a84963
 
 
 
 
 
 
 
 
e383754
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a84963
e383754
3a84963
 
e383754
b8778f9
e383754
 
 
 
 
b8778f9
 
e383754
b96ab7a
 
 
 
 
3a84963
 
 
 
 
 
 
b96ab7a
3a84963
 
b96ab7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a84963
 
b96ab7a
 
3a84963
 
 
 
 
b96ab7a
e383754
b96ab7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e383754
b96ab7a
3a84963
 
 
 
 
e383754
b96ab7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e383754
b96ab7a
e383754
3a84963
 
 
e383754
3a84963
e383754
3a84963
 
 
 
 
 
 
e383754
 
 
 
 
3a84963
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e383754
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a84963
 
 
 
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
/**
 * Map initialization and GeoJSON visualization
 * This file handles the map creation and displaying GeoJSON data on it
 */

// Store the map object globally
let map = null;
let currentFeatureType = 'buildings';

// Initialize the map with default settings
function initMap(initialCoords) {
    // If map already exists, remove it and create a new one
    if (map !== null) {
        map.remove();
    }

    // Default center coordinates (will be overridden by GeoJSON data)
    let center = [0, 0];
    let zoom = 2;

    // If coordinates are provided, use them
    if (initialCoords && initialCoords.lat !== undefined && initialCoords.lng !== undefined) {
        center = [initialCoords.lat, initialCoords.lng];
        zoom = initialCoords.zoom || 13;
    }

    // Initialize the map with the center coordinates
    map = L.map('map').setView(center, zoom);

    // Define tile layers
    const osmLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
        maxZoom: 19
    });

    const satelliteLayer = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
        attribution: 'Imagery &copy; Esri',
        maxZoom: 19
    });

    // Add OpenStreetMap layer by default
    osmLayer.addTo(map);

    // Add layer control
    const baseLayers = {
        "OpenStreetMap": osmLayer,
        "Satellite": satelliteLayer
    };

    L.control.layers(baseLayers, null, {position: 'topright'}).addTo(map);

    // Add a scale control
    L.control.scale().addTo(map);

    return map;
}

// Display GeoJSON data on the map
function displayGeoJSON(geojsonData) {
    // Log the GeoJSON data for debugging
    console.log('GeoJSON data received:', geojsonData);

    if (geojsonData && geojsonData.features && geojsonData.features.length > 0) {
        console.log('First feature:', geojsonData.features[0]);
        if (geojsonData.features[0].geometry && geojsonData.features[0].geometry.coordinates) {
            console.log('First feature coordinates:',
                geojsonData.features[0].geometry.type === 'Polygon' ?
                geojsonData.features[0].geometry.coordinates[0][0] :
                geojsonData.features[0].geometry.coordinates[0][0][0]);
        }
    }

    // Calculate center coordinates from GeoJSON data
    let initialCoords = calculateCenterFromGeoJSON(geojsonData);
    console.log('Calculated center coordinates:', initialCoords);

    if (!map) {
        initMap(initialCoords);
    }

    // Switch to satellite view for better context when viewing features
    if (geojsonData && geojsonData.features && geojsonData.features.length > 0) {
        // Switch to satellite view for better visualization
        try {
            document.querySelectorAll('.leaflet-control-layers-base input')[1].click();
        } catch (e) {
            console.warn('Could not switch to satellite view:', e);
        }
    }

    // Update feature type if available in the data
    if (geojsonData && geojsonData.feature_type) {
        currentFeatureType = geojsonData.feature_type;
    }

    // Clear any existing GeoJSON layers
    map.eachLayer(function(layer) {
        if (layer instanceof L.GeoJSON) {
            map.removeLayer(layer);
        }
    });

    // Add the GeoJSON data to the map with styling based on feature type
    const geojsonLayer = L.geoJSON(geojsonData, {
        style: function(feature) {
            // Different styling based on feature type
            switch(currentFeatureType) {
                case 'buildings':
                    return {
                        fillColor: '#e63946',
                        weight: 1.5,
                        opacity: 1,
                        color: '#999',
                        fillOpacity: 0.7
                    };
                case 'trees':
                    return {
                        fillColor: '#2a9d8f',
                        weight: 1,
                        opacity: 0.9,
                        color: '#006d4f',
                        fillOpacity: 0.7
                    };
                case 'water':
                    return {
                        fillColor: '#0077b6',
                        weight: 1,
                        opacity: 0.8,
                        color: '#023e8a',
                        fillOpacity: 0.6
                    };
                case 'roads':
                    return {
                        fillColor: '#a8dadc',
                        weight: 3,
                        opacity: 1,
                        color: '#457b9d',
                        fillOpacity: 0.8
                    };
                default:
                    return {
                        fillColor: getRandomColor(),
                        weight: 2,
                        opacity: 1,
                        color: '#666',
                        fillOpacity: 0.7
                    };
            }
        },
        pointToLayer: function(feature, latlng) {
            // Style points based on feature type
            let pointStyle = {
                radius: 8,
                color: "#000",
                weight: 1,
                opacity: 1,
                fillOpacity: 0.8
            };

            // Set color based on feature type
            switch(currentFeatureType) {
                case 'buildings':
                    pointStyle.fillColor = '#e63946';
                    break;
                case 'trees':
                    pointStyle.fillColor = '#2a9d8f';
                    break;
                case 'water':
                    pointStyle.fillColor = '#0077b6';
                    break;
                case 'roads':
                    pointStyle.fillColor = '#a8dadc';
                    break;
                default:
                    pointStyle.fillColor = getRandomColor();
            }

            return L.circleMarker(latlng, pointStyle);
        },
        onEachFeature: function(feature, layer) {
            // Add popups to show feature properties
            if (feature.properties) {
                let popupContent = '<div class="feature-popup">';

                // Set title based on feature type
                let title = 'Feature';
                switch(currentFeatureType) {
                    case 'buildings':
                        title = 'Building';
                        break;
                    case 'trees':
                        title = 'Tree/Vegetation';
                        break;
                    case 'water':
                        title = 'Water Body';
                        break;
                    case 'roads':
                        title = 'Road';
                        break;
                }

                popupContent += `<h5>${title} Properties</h5>`;

                for (const [key, value] of Object.entries(feature.properties)) {
                    popupContent += `<strong>${key}:</strong> ${value}<br>`;
                }

                popupContent += '</div>';

                layer.bindPopup(popupContent);
            }
        }
    }).addTo(map);

    // Zoom to fit the GeoJSON data bounds
    if (geojsonLayer.getBounds().isValid()) {
        const bounds = geojsonLayer.getBounds();
        console.log('GeoJSON bounds:', bounds);
        map.fitBounds(bounds);
    } else {
        console.warn('GeoJSON bounds not valid');
    }
}

// Generate a random color for styling different features
function getRandomColor() {
    const colors = [
        '#3388ff', '#33a02c', '#1f78b4', '#ff7f00', '#6a3d9a',
        '#a6cee3', '#b2df8a', '#fb9a99', '#fdbf6f', '#cab2d6'
    ];
    return colors[Math.floor(Math.random() * colors.length)];
}

// Function to format GeoJSON for display
function formatGeoJSON(geojson) {
    return JSON.stringify(geojson, null, 2);
}

// Calculate center coordinates from GeoJSON data
function calculateCenterFromGeoJSON(geojsonData) {
    if (!geojsonData || !geojsonData.features || geojsonData.features.length === 0) {
        return { lat: 0, lng: 0, zoom: 2 }; // Default to world view
    }

    try {
        // Create a temporary GeoJSON layer to calculate bounds
        const tempLayer = L.geoJSON(geojsonData);
        const bounds = tempLayer.getBounds();

        if (bounds.isValid()) {
            const center = bounds.getCenter();
            // Calculate appropriate zoom level based on bounds size
            const zoom = getBoundsZoomLevel(bounds);
            return { lat: center.lat, lng: center.lng, zoom: zoom };
        }
    } catch (e) {
        console.warn('Error calculating center from GeoJSON:', e);
    }

    // If we can't calculate from features, try to get center from the first feature
    try {
        const firstFeature = geojsonData.features[0];
        if (firstFeature.geometry && firstFeature.geometry.coordinates) {
            let coords;

            // Handle different geometry types
            if (firstFeature.geometry.type === 'Point') {
                coords = firstFeature.geometry.coordinates;
                return { lat: coords[1], lng: coords[0], zoom: 15 };
            } else if (firstFeature.geometry.type === 'Polygon') {
                coords = firstFeature.geometry.coordinates[0][0];
                return { lat: coords[1], lng: coords[0], zoom: 13 };
            } else if (firstFeature.geometry.type === 'MultiPolygon') {
                coords = firstFeature.geometry.coordinates[0][0][0];
                return { lat: coords[1], lng: coords[0], zoom: 13 };
            }
        }
    } catch (e) {
        console.warn('Error getting coordinates from first feature:', e);
    }

    // Default fallback
    return { lat: 0, lng: 0, zoom: 2 };
}

// Calculate appropriate zoom level based on bounds size
function getBoundsZoomLevel(bounds) {
    const WORLD_DIM = { height: 256, width: 256 };
    const ZOOM_MAX = 18;

    const ne = bounds.getNorthEast();
    const sw = bounds.getSouthWest();

    const latFraction = (ne.lat - sw.lat) / 180;
    const lngFraction = (ne.lng - sw.lng) / 360;

    const latZoom = Math.floor(Math.log(1 / latFraction) / Math.LN2);
    const lngZoom = Math.floor(Math.log(1 / lngFraction) / Math.LN2);

    const zoom = Math.min(latZoom, lngZoom, ZOOM_MAX);

    return zoom > 0 ? zoom - 1 : 0; // Zoom out slightly for better context
}

// Initialize map when the DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
    // The map will be initialized when results are available
});