SmartCane/webapps/geojson_viewer.html

1571 lines
50 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GeoJSON Viewer</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.css" />
<link rel="stylesheet" href="theme.css">
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
}
.container {
max-width: 1400px;
margin: 0 auto;
background: white;
border-radius: 12px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
overflow: hidden;
}
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
text-align: center;
}
.header h1 {
font-size: 2.5em;
margin-bottom: 10px;
}
.header p {
font-size: 1.1em;
opacity: 0.9;
}
.map-controls {
position: absolute;
top: 20px;
right: 20px;
z-index: 400;
background: white;
padding: 12px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 12px;
}
.map-controls label {
display: flex;
align-items: center;
gap: 8px;
cursor: pointer;
font-size: 0.9em;
color: #333;
font-weight: 500;
}
.map-controls-group {
display: flex;
flex-direction: column;
gap: 8px;
border-top: 1px solid #e0e0e0;
padding-top: 8px;
}
.map-controls-group:first-child {
border-top: none;
padding-top: 0;
}
.toggle-switch {
position: relative;
display: inline-block;
width: 50px;
height: 24px;
}
.toggle-switch input {
opacity: 0;
width: 0;
height: 0;
}
.toggle-slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
transition: 0.3s;
border-radius: 24px;
}
.toggle-slider:before {
position: absolute;
content: "";
height: 18px;
width: 18px;
left: 3px;
bottom: 3px;
background-color: white;
transition: 0.3s;
border-radius: 50%;
}
input:checked + .toggle-slider {
background-color: #667eea;
}
input:checked + .toggle-slider:before {
transform: translateX(26px);
}
.toggle-label {
font-size: 0.85em;
color: #666;
min-width: 60px;
text-align: right;
}
.content {
display: flex;
height: calc(100vh - 200px);
gap: 0;
}
.sidebar {
width: 350px;
background: #f8f9fa;
border-right: 1px solid #e0e0e0;
padding: 25px;
overflow-y: auto;
}
.map-container {
flex: 1;
position: relative;
background: #e0e0e0;
}
#map {
width: 100%;
height: 100%;
}
.upload-section {
margin-bottom: 30px;
}
.upload-section h2 {
font-size: 1.2em;
color: #333;
margin-bottom: 15px;
display: flex;
align-items: center;
gap: 8px;
}
.file-input-wrapper {
position: relative;
display: block;
}
.file-input-label {
display: block;
padding: 15px 20px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border-radius: 8px;
cursor: pointer;
text-align: center;
font-weight: 600;
transition: transform 0.2s, box-shadow 0.2s;
border: 2px dashed transparent;
}
.file-input-label:hover {
transform: translateY(-2px);
box-shadow: 0 8px 16px rgba(102, 126, 234, 0.4);
}
input[type="file"] {
display: none;
}
.file-name {
margin-top: 10px;
padding: 10px;
background: #e3f2fd;
border-left: 4px solid #2196f3;
border-radius: 4px;
font-size: 0.9em;
color: #1565c0;
display: none;
}
.file-name.active {
display: block;
}
.stats-section {
margin-bottom: 30px;
padding: 15px;
background: white;
border-radius: 8px;
border-left: 4px solid #667eea;
}
.stat-item {
display: flex;
justify-content: space-between;
padding: 8px 0;
border-bottom: 1px solid #f0f0f0;
font-size: 0.95em;
}
.stat-item:last-child {
border-bottom: none;
}
.stat-label {
color: #666;
font-weight: 500;
}
.stat-value {
color: #333;
font-weight: 600;
}
.features-section h2 {
font-size: 1.2em;
color: #333;
margin-bottom: 15px;
display: flex;
align-items: center;
gap: 8px;
}
.features-list {
display: flex;
flex-direction: column;
gap: 8px;
max-height: 400px;
overflow-y: auto;
}
.feature-item {
padding: 10px;
background: white;
border: 1px solid #e0e0e0;
border-radius: 6px;
cursor: pointer;
transition: all 0.2s;
font-size: 0.9em;
color: #333;
}
.feature-item:hover {
background: #f0f0f0;
border-color: #667eea;
transform: translateX(4px);
}
.feature-item.active {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border-color: transparent;
}
.properties-section {
margin-top: 20px;
padding: 15px;
background: white;
border-radius: 8px;
border-left: 4px solid #667eea;
display: none;
}
.properties-section.active {
display: block;
}
.properties-section h3 {
font-size: 1em;
color: #333;
margin-bottom: 12px;
}
.property-row {
display: flex;
flex-direction: column;
padding: 8px 0;
border-bottom: 1px solid #f0f0f0;
font-size: 0.85em;
}
.property-row:last-child {
border-bottom: none;
}
.property-key {
color: #666;
font-weight: 600;
margin-bottom: 4px;
}
.property-value {
color: #333;
word-break: break-word;
background: #f5f5f5;
padding: 6px;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 0.8em;
}
.no-data {
text-align: center;
color: #999;
padding: 20px;
font-size: 0.95em;
}
.controls-section {
margin-bottom: 20px;
display: flex;
gap: 8px;
}
button {
flex: 1;
padding: 10px;
background: #f0f0f0;
border: 1px solid #ddd;
border-radius: 6px;
cursor: pointer;
font-size: 0.9em;
color: #333;
transition: all 0.2s;
}
button:hover {
background: #e0e0e0;
border-color: #999;
}
button.danger {
background: #ffebee;
color: #c62828;
border-color: #ef5350;
}
button.danger:hover {
background: #ffcdd2;
}
.spinner {
display: inline-block;
width: 16px;
height: 16px;
border: 3px solid #f3f3f3;
border-top: 3px solid #667eea;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.tooltip {
background: rgba(0, 0, 0, 0.8);
color: white;
padding: 8px 12px;
border-radius: 4px;
font-size: 0.85em;
white-space: nowrap;
z-index: 1000;
}
@media (max-width: 1024px) {
.content {
flex-direction: column;
height: auto;
}
.sidebar {
width: 100%;
border-right: none;
border-bottom: 1px solid #e0e0e0;
max-height: 300px;
}
#map {
height: 500px;
}
}
.error-message {
padding: 12px;
background: #ffebee;
color: #c62828;
border: 1px solid #ef5350;
border-radius: 6px;
margin-bottom: 15px;
display: none;
font-size: 0.9em;
}
.error-message.active {
display: block;
}
.success-message {
padding: 12px;
background: #e8f5e9;
color: #2e7d32;
border: 1px solid #66bb6a;
border-radius: 6px;
margin-bottom: 15px;
display: none;
font-size: 0.9em;
}
.success-message.active {
display: block;
}
/* Modal Popup Styles */
.modal {
display: none;
position: fixed;
z-index: 1000;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
animation: fadeIn 0.3s ease;
}
.modal.active {
display: flex;
align-items: center;
justify-content: center;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.modal-content {
background: white;
border-radius: 12px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
max-width: 500px;
width: 90%;
max-height: 80vh;
overflow-y: auto;
animation: slideUp 0.3s ease;
}
@keyframes slideUp {
from {
transform: translateY(50px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
.modal-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 20px;
border-radius: 12px 12px 0 0;
display: flex;
justify-content: space-between;
align-items: center;
}
.modal-header h2 {
margin: 0;
font-size: 1.5em;
}
.modal-close {
background: rgba(255, 255, 255, 0.2);
border: none;
color: white;
font-size: 24px;
cursor: pointer;
padding: 0;
width: 30px;
height: 30px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
transition: background 0.2s;
}
.modal-close:hover {
background: rgba(255, 255, 255, 0.3);
}
.modal-body {
padding: 25px;
}
.modal-property {
display: flex;
flex-direction: column;
margin-bottom: 20px;
padding-bottom: 20px;
border-bottom: 1px solid #e0e0e0;
}
.modal-property:last-child {
border-bottom: none;
margin-bottom: 0;
padding-bottom: 0;
}
.modal-property-key {
font-weight: 700;
color: #333;
font-size: 0.95em;
margin-bottom: 8px;
color: #667eea;
}
.modal-property-value {
color: #555;
font-size: 0.95em;
line-height: 1.5;
word-break: break-word;
background: #f8f9fa;
padding: 12px;
border-radius: 6px;
font-family: 'Courier New', monospace;
font-size: 0.9em;
}
.modal-empty {
text-align: center;
color: #999;
padding: 40px 20px;
}
.summary-section {
margin-bottom: 25px;
padding: 20px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 8px;
color: white;
}
.summary-section h2 {
font-size: 1.1em;
margin-bottom: 15px;
display: flex;
align-items: center;
gap: 8px;
}
.summary-stat {
display: flex;
justify-content: space-between;
padding: 8px 0;
border-bottom: 1px solid rgba(255, 255, 255, 0.2);
font-size: 0.95em;
}
.summary-stat:last-child {
border-bottom: none;
}
.summary-label {
font-weight: 500;
opacity: 0.9;
}
.summary-value {
font-weight: 600;
text-align: right;
}
.table-section {
margin-bottom: 20px;
}
.table-section h3 {
font-size: 1.1em;
color: #333;
margin-bottom: 12px;
display: flex;
align-items: center;
gap: 8px;
}
.attribute-table {
width: 100%;
border-collapse: collapse;
background: white;
border: 1px solid #e0e0e0;
border-radius: 6px;
overflow: hidden;
font-size: 0.85em;
}
.attribute-table thead {
background: #f5f5f5;
border-bottom: 2px solid #ddd;
}
.attribute-table th {
padding: 10px;
text-align: left;
font-weight: 600;
color: #333;
border-right: 1px solid #e0e0e0;
}
.attribute-table th:last-child {
border-right: none;
}
.attribute-table td {
padding: 10px;
border-right: 1px solid #e0e0e0;
border-bottom: 1px solid #f0f0f0;
color: #555;
word-break: break-word;
}
.attribute-table td:last-child {
border-right: none;
}
.attribute-table tbody tr:hover {
background: #f9f9f9;
}
.attribute-table tbody tr:last-child td {
border-bottom: none;
}
.table-wrapper {
overflow-x: auto;
max-height: 400px;
overflow-y: auto;
border: 1px solid #e0e0e0;
border-radius: 6px;
}
@media (max-width: 1024px) {
.attribute-table {
font-size: 0.75em;
}
.attribute-table th,
.attribute-table td {
padding: 6px;
}
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>📍 GeoJSON Viewer</h1>
<p>Upload a GeoJSON file to visualize features on an interactive map</p>
</div>
<div class="content">
<div class="sidebar">
<div class="error-message" id="errorMessage"></div>
<div class="success-message" id="successMessage"></div>
<div class="summary-section" id="summarySection" style="display: none;">
<h2>📊 Project Summary</h2>
<div class="summary-stat">
<span class="summary-label">Client/Project:</span>
<span class="summary-value" id="clientName">-</span>
</div>
<div class="summary-stat">
<span class="summary-label">Total Fields:</span>
<span class="summary-value" id="totalFields">0</span>
</div>
<div class="summary-stat">
<span class="summary-label">Total Area (ha):</span>
<span class="summary-value" id="totalHectares">0</span>
</div>
<div class="summary-stat">
<span class="summary-label">Total Area (acres):</span>
<span class="summary-value" id="totalAcres">0</span>
</div>
</div>
<div class="upload-section">
<h2>📁 Upload File</h2>
<div class="file-input-wrapper">
<label for="geojsonFile" class="file-input-label">
Choose GeoJSON File
</label>
<input type="file" id="geojsonFile" accept=".geojson,.json" />
<div class="file-name" id="fileName"></div>
</div>
</div>
<div class="controls-section">
<button id="clearBtn" title="Clear all data">Clear All</button>
<button id="downloadBtn" title="Download current GeoJSON" style="display: none;">Download</button>
</div>
<div class="stats-section" id="statsSection" style="display: none;">
<div class="stat-item">
<span class="stat-label">Features:</span>
<span class="stat-value" id="featureCount">0</span>
</div>
<div class="stat-item">
<span class="stat-label">Type:</span>
<span class="stat-value" id="geomType">-</span>
</div>
<div class="stat-item">
<span class="stat-label">Bounds:</span>
<span class="stat-value" id="bounds">-</span>
</div>
</div>
<div class="table-section" id="tableSection" style="display: none;">
<h3>📋 Attribute Table</h3>
<div class="table-wrapper">
<table class="attribute-table" id="attributeTable">
<thead>
<tr id="tableHeader"></tr>
</thead>
<tbody id="tableBody"></tbody>
</table>
</div>
</div>
<div class="features-section" id="featuresSection" style="display: none;">
<h2>🗺️ Features</h2>
<div style="margin-bottom: 15px;">
<input
type="text"
id="featureSearch"
placeholder="Search by field code..."
style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; font-size: 0.9em; box-sizing: border-box;"
/>
</div>
<div class="features-list" id="featuresList"></div>
</div>
<div class="properties-section" id="propertiesSection">
<h3>📋 Properties</h3>
<div id="propertiesContent" class="no-data">Select a feature to view properties</div>
</div>
</div>
<div class="map-container">
<div id="map"></div>
<div class="map-controls">
<div class="map-controls-group">
<label for="mapToggle">
<span class="toggle-label" id="mapTypeLabel">OSM</span>
<div class="toggle-switch">
<input type="checkbox" id="mapToggle">
<span class="toggle-slider"></span>
</div>
<span>🛰️</span>
</label>
</div>
<div class="map-controls-group">
<label for="labelsToggle">
<div class="toggle-switch">
<input type="checkbox" id="labelsToggle">
<span class="toggle-slider"></span>
</div>
<span>Show Labels</span>
</label>
</div>
</div>
</div>
</div>
<!-- Feature Details Modal -->
<div class="modal" id="featureModal">
<div class="modal-content">
<div class="modal-header">
<h2 id="modalTitle">Feature Details</h2>
<button class="modal-close" onclick="closeFeatureModal()">&times;</button>
</div>
<div class="modal-body" id="modalBody"></div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.js"></script>
<script>
// Initialize map layers
const osmLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors',
maxZoom: 19
});
const satelliteLayer = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
attribution: '© Esri, DigitalGlobe, Earthstar Geographics, CNES/Airbus DS, USDA, USGS, AeroGRID, IGN, and the GIS User Community',
maxZoom: 18
});
// Initialize map
const map = L.map('map').setView([0, 0], 2);
osmLayer.addTo(map);
let currentLayer = 'osm';
let geojsonLayer = null;
let labelsLayer = null;
let currentGeojsonData = null;
let featuresList = [];
let showLabels = false;
// Toggle map layer
const mapToggle = document.getElementById('mapToggle');
const mapTypeLabel = document.getElementById('mapTypeLabel');
mapToggle.addEventListener('change', () => {
if (mapToggle.checked) {
// Switch to satellite
map.removeLayer(osmLayer);
satelliteLayer.addTo(map);
mapTypeLabel.textContent = 'SAT';
currentLayer = 'satellite';
} else {
// Switch to OSM
map.removeLayer(satelliteLayer);
osmLayer.addTo(map);
mapTypeLabel.textContent = 'OSM';
currentLayer = 'osm';
}
});
// Toggle labels visibility
const labelsToggle = document.getElementById('labelsToggle');
labelsToggle.addEventListener('change', () => {
showLabels = labelsToggle.checked;
if (!labelsLayer) {
console.warn('Labels layer not initialized');
return;
}
if (showLabels) {
labelsLayer.addTo(map);
updateLabelsVisibility();
} else {
map.removeLayer(labelsLayer);
}
});
// Elements
const geojsonInput = document.getElementById('geojsonFile');
const fileNameDisplay = document.getElementById('fileName');
const errorMessage = document.getElementById('errorMessage');
const successMessage = document.getElementById('successMessage');
const statsSection = document.getElementById('statsSection');
const featuresSection = document.getElementById('featuresSection');
const propertiesSection = document.getElementById('propertiesSection');
const propertiesContent = document.getElementById('propertiesContent');
const featureCountEl = document.getElementById('featureCount');
const geomTypeEl = document.getElementById('geomType');
const boundsEl = document.getElementById('bounds');
const featureLst = document.getElementById('featuresList');
const clearBtn = document.getElementById('clearBtn');
const downloadBtn = document.getElementById('downloadBtn');
const featureModal = document.getElementById('featureModal');
const modalTitle = document.getElementById('modalTitle');
const modalBody = document.getElementById('modalBody');
const summarySection = document.getElementById('summarySection');
const tableSection = document.getElementById('tableSection');
const clientNameEl = document.getElementById('clientName');
const totalFieldsEl = document.getElementById('totalFields');
const totalHectaresEl = document.getElementById('totalHectares');
const totalAcresEl = document.getElementById('totalAcres');
const featureSearch = document.getElementById('featureSearch');
// Show message
function showMessage(message, type = 'error') {
const el = type === 'error' ? errorMessage : successMessage;
el.textContent = message;
el.classList.add('active');
setTimeout(() => el.classList.remove('active'), 5000);
}
// Calculate area in square meters using Turf.js
function getFeatureArea(feature) {
try {
if (!feature.geometry) return 0;
const geomType = feature.geometry.type;
if (geomType === 'Point') return 0;
if (geomType === 'LineString' || geomType === 'MultiLineString') return 0;
// Use Haversine formula for rough area calculation
const coords = feature.geometry.coordinates;
if (geomType === 'Polygon') {
return calculatePolygonArea(coords[0]);
} else if (geomType === 'MultiPolygon') {
return coords.reduce((total, polygon) => total + calculatePolygonArea(polygon[0]), 0);
}
} catch (e) {
console.warn('Error calculating area:', e);
return 0;
}
return 0;
}
// Calculate polygon area using Shoelace formula
function calculatePolygonArea(coords) {
if (!coords || coords.length < 3) return 0;
let area = 0;
const R = 6371000; // Earth radius in meters
for (let i = 0; i < coords.length - 1; i++) {
const p1 = coords[i];
const p2 = coords[i + 1];
const lat1 = (p1[1] * Math.PI) / 180;
const lat2 = (p2[1] * Math.PI) / 180;
const dLng = ((p2[0] - p1[0]) * Math.PI) / 180;
area += Math.sin(lat1) * Math.cos(lat1) * dLng;
area += Math.sin(lat1) * Math.cos(lat2) * Math.sin(dLng);
}
area = Math.abs(area * R * R / 2);
return area;
}
// Convert square meters to hectares and acres
function convertArea(squareMeters) {
const hectares = squareMeters / 10000;
const acres = squareMeters / 4046.856;
return { hectares, acres };
}
// Get first property key (field code)
function getFirstPropertyValue(properties) {
if (!properties) return '';
const keys = Object.keys(properties);
if (keys.length === 0) return '';
return properties[keys[0]];
}
// Create labels layer from features
function createLabelsLayer(features) {
labelsLayer = L.featureGroup([]);
// First pass: collect all label positions
const labelPositions = [];
features.forEach((feature, index) => {
const props = feature.properties || {};
const fieldCode = getFirstPropertyValue(props);
const displayLabel = fieldCode || `Feature ${index + 1}`;
if (feature.geometry && feature.geometry.type !== 'Point') {
// Get centroid for polygon features
const bounds = L.geoJSON(feature).getBounds();
const center = bounds.getCenter();
labelPositions.push({
fieldName: displayLabel,
latlng: center,
originalLatlng: center,
iconAnchor: [0, 0],
isPoint: false
});
} else if (feature.geometry && feature.geometry.type === 'Point') {
// For points, add label above the marker
const latlng = L.GeoJSON.coordsToLatLng(feature.geometry.coordinates);
labelPositions.push({
fieldName: displayLabel,
latlng: latlng,
originalLatlng: latlng,
iconAnchor: [0, 30],
isPoint: true
});
}
});
// Create markers
labelPositions.forEach((pos) => {
const label = L.marker(pos.latlng, {
icon: L.divIcon({
className: 'field-label',
html: `<div style="
background: rgba(102, 126, 234, 0.9);
color: white;
padding: 4px 8px;
border-radius: 4px;
font-size: 14px;
font-weight: 600;
white-space: nowrap;
box-shadow: 0 2px 4px rgba(0,0,0,0.2);
border: 2px solid white;
pointer-events: none;
text-align: center;
max-width: 200px;
overflow: hidden;
text-overflow: ellipsis;
">${pos.fieldName}</div>`,
iconSize: [null, null],
iconAnchor: pos.iconAnchor
}),
interactive: false
});
labelsLayer.addLayer(label);
});
}
// Update labels visibility based on zoom level
function updateLabelsVisibility() {
const zoomLevel = map.getZoom();
const minZoomForLabels = 16; // Only show labels at zoom level 13 and above
if (labelsLayer && showLabels) {
if (zoomLevel >= minZoomForLabels) {
labelsLayer.eachLayer(layer => {
layer.setOpacity(1);
});
} else {
labelsLayer.eachLayer(layer => {
layer.setOpacity(0);
});
}
}
}
// Show message
function showMessage(message, type = 'error') {
const el = type === 'error' ? errorMessage : successMessage;
el.textContent = message;
el.classList.add('active');
setTimeout(() => el.classList.remove('active'), 5000);
}
// Handle file upload
geojsonInput.addEventListener('change', (e) => {
const file = e.target.files[0];
if (!file) return;
fileNameDisplay.textContent = `📄 ${file.name}`;
fileNameDisplay.classList.add('active');
const reader = new FileReader();
reader.onload = (event) => {
try {
const geojson = JSON.parse(event.target.result);
const success = loadGeojson(geojson, file.name);
if (success) {
showMessage('GeoJSON loaded successfully!', 'success');
}
} catch (error) {
showMessage(`Error parsing file: ${error.message}`, 'error');
}
};
reader.onerror = () => {
showMessage('Error reading file', 'error');
};
reader.readAsText(file);
});
// Validate CRS
function validateCRS(geojson) {
// If no CRS is specified, assume WGS84 (default for GeoJSON)
if (!geojson.crs) {
return { valid: true, message: 'No CRS specified (default WGS84)' };
}
const crs = geojson.crs;
let crsName = '';
// Extract CRS name from different possible formats
if (crs.properties && crs.properties.name) {
crsName = crs.properties.name;
} else if (typeof crs === 'string') {
crsName = crs;
}
// Check if it's WGS84 (various possible names)
const wgs84Variations = [
'EPSG:4326',
'epsg:4326',
'urn:ogc:def:crs:EPSG::4326',
'urn:ogc:def:crs:EPSG:4.3:4326',
'WGS84',
'wgs84',
'urn:ogc:def:crs:OGC:1.3:CRS84'
];
const isWGS84 = wgs84Variations.some(variant =>
crsName.toUpperCase().includes(variant.toUpperCase())
);
if (isWGS84) {
return { valid: true, message: 'CRS: WGS84' };
} else {
return {
valid: false,
message: `Non-supported CRS (${JSON.stringify(crs)})`
};
}
}
// Load and display GeoJSON
function loadGeojson(geojson, fileName) {
// Validate CRS first
const crsValidation = validateCRS(geojson);
if (!crsValidation.valid) {
showMessage(crsValidation.message, 'error');
return false;
}
// Clear previous layer
if (geojsonLayer) {
map.removeLayer(geojsonLayer);
}
// Clear previous labels
if (labelsLayer) {
map.removeLayer(labelsLayer);
}
currentGeojsonData = geojson;
featuresList = [];
// Handle both FeatureCollection and individual features
const features = geojson.type === 'FeatureCollection'
? geojson.features
: [geojson];
if (features.length === 0) {
showMessage('GeoJSON contains no features', 'error');
return false;
}
// Create layer with popups
geojsonLayer = L.geoJSON(geojson, {
onEachFeature: (feature, layer) => {
const index = featuresList.length;
featuresList.push({ feature, layer, index });
// Add click handler to open modal
layer.on('click', (e) => {
L.DomEvent.stopPropagation(e);
openFeatureModal(feature);
selectFeature(index);
});
// Hover effect
layer.on('mouseover', () => {
if (layer.setStyle) {
layer.setStyle({
weight: 3,
opacity: 1,
dashArray: ''
});
}
});
layer.on('mouseout', () => {
if (layer.setStyle) {
geojsonLayer.resetStyle(layer);
}
});
},
style: {
color: '#667eea',
weight: 2,
opacity: 0.7,
fillOpacity: 0.5
},
pointToLayer: (feature, latlng) => {
return L.circleMarker(latlng, {
radius: 8,
fillColor: '#667eea',
color: '#fff',
weight: 2,
opacity: 1,
fillOpacity: 0.8
});
}
}).addTo(map);
// Create labels layer
createLabelsLayer(features);
// Fit bounds
const bounds = geojsonLayer.getBounds();
map.fitBounds(bounds, { padding: [50, 50] });
// Update labels visibility based on zoom level
updateLabelsVisibility();
map.on('zoom', updateLabelsVisibility);
// Update stats
updateStats(geojson, features);
// Display features list
displayFeaturesList();
// Build attribute table
buildAttributeTable(features);
// Calculate and display summary
updateSummary(geojson, features);
// Show/hide elements
summarySection.style.display = 'block';
statsSection.style.display = 'block';
featuresSection.style.display = 'block';
tableSection.style.display = 'block';
downloadBtn.style.display = 'block';
return true;
}
// Update statistics
function updateStats(geojson, features) {
featureCountEl.textContent = features.length;
// Get geometry type
const types = new Set();
features.forEach(f => {
if (f.geometry) {
types.add(f.geometry.type);
}
});
geomTypeEl.textContent = Array.from(types).join(', ') || '-';
// Get bounds
const bounds = geojsonLayer.getBounds();
const sw = bounds.getSouthWest();
const ne = bounds.getNorthEast();
boundsEl.textContent = `[${sw.lat.toFixed(2)}, ${sw.lng.toFixed(2)}] - [${ne.lat.toFixed(2)}, ${ne.lng.toFixed(2)}]`;
}
// Display features list
function displayFeaturesList() {
featureLst.innerHTML = '';
featureSearch.value = '';
featuresList.forEach((item, index) => {
const div = document.createElement('div');
div.className = 'feature-item';
// Get first property value (field code)
const props = item.feature.properties || {};
const fieldCode = getFirstPropertyValue(props);
const name = fieldCode || `Feature ${index + 1}`;
div.textContent = name;
div.dataset.index = index;
div.addEventListener('click', () => selectFeature(index));
featureLst.appendChild(div);
});
}
// Select feature
function selectFeature(index) {
const item = featuresList[index];
if (!item) {
console.error('Feature not found at index:', index);
return;
}
// Update feature list UI
document.querySelectorAll('.feature-item').forEach((el, i) => {
el.classList.toggle('active', i === index);
});
// Display properties in sidebar
displayProperties(item.feature);
// Open modal with properties
openFeatureModal(item.feature);
// Zoom to feature on map
setTimeout(() => {
try {
if (item.feature.geometry.type === 'Point') {
const latlng = item.layer.getLatLng();
map.setView(latlng, 14);
} else {
const bounds = L.geoJSON(item.feature).getBounds();
map.fitBounds(bounds, { padding: [100, 100] });
}
} catch (e) {
console.error('Error zooming to feature:', e);
}
}, 100);
// Update map styling
if (item.layer.setStyle) {
item.layer.setStyle({
weight: 3,
opacity: 1
});
}
}
// Display properties
function displayProperties(feature) {
propertiesSection.classList.add('active');
propertiesContent.innerHTML = '';
const props = feature.properties || {};
if (Object.keys(props).length === 0) {
propertiesContent.innerHTML = '<div class="no-data">No properties</div>';
return;
}
Object.entries(props).forEach(([key, value]) => {
const row = document.createElement('div');
row.className = 'property-row';
const keyEl = document.createElement('div');
keyEl.className = 'property-key';
keyEl.textContent = key;
const valueEl = document.createElement('div');
valueEl.className = 'property-value';
valueEl.textContent = typeof value === 'object'
? JSON.stringify(value, null, 2)
: value;
row.appendChild(keyEl);
row.appendChild(valueEl);
propertiesContent.appendChild(row);
});
}
// Build attribute table
function buildAttributeTable(features) {
const tableHeader = document.getElementById('tableHeader');
const tableBody = document.getElementById('tableBody');
tableHeader.innerHTML = '';
tableBody.innerHTML = '';
if (features.length === 0) return;
// Collect all unique property keys
const allKeys = new Set();
features.forEach(f => {
if (f.properties) {
Object.keys(f.properties).forEach(key => allKeys.add(key));
}
});
// Add area columns
allKeys.add('Area (ha)');
allKeys.add('Area (acres)');
// Create header
const headerKeys = Array.from(allKeys);
headerKeys.forEach(key => {
const th = document.createElement('th');
th.textContent = key;
tableHeader.appendChild(th);
});
// Create rows
features.forEach((feature, idx) => {
const row = document.createElement('tr');
row.style.cursor = 'pointer';
row.addEventListener('click', () => selectFeature(idx));
row.addEventListener('mouseover', () => row.style.backgroundColor = '#f0f0f0');
row.addEventListener('mouseout', () => row.style.backgroundColor = '');
const props = feature.properties || {};
const areaM2 = getFeatureArea(feature);
const { hectares, acres } = convertArea(areaM2);
headerKeys.forEach(key => {
const td = document.createElement('td');
if (key === 'Area (ha)') {
td.textContent = hectares.toFixed(2);
} else if (key === 'Area (acres)') {
td.textContent = acres.toFixed(2);
} else {
td.textContent = props[key] !== undefined ? props[key] : '-';
}
row.appendChild(td);
});
tableBody.appendChild(row);
});
}
// Update summary section
function updateSummary(geojson, features) {
// Try to get client name from GeoJSON properties or filename
let clientName = 'Unknown Project';
if (geojson.name) {
clientName = geojson.name;
} else if (geojson.properties && geojson.properties.name) {
clientName = geojson.properties.name;
}
// Calculate totals
let totalHa = 0;
let totalAc = 0;
features.forEach(feature => {
const areaM2 = getFeatureArea(feature);
const { hectares, acres } = convertArea(areaM2);
totalHa += hectares;
totalAc += acres;
});
// Update UI
clientNameEl.textContent = clientName;
totalFieldsEl.textContent = features.length;
totalHectaresEl.textContent = totalHa.toFixed(2);
totalAcresEl.textContent = totalAc.toFixed(2);
}
// Open feature modal
function openFeatureModal(feature) {
const props = feature.properties || {};
const featureName = props.name || props.id || 'Feature Details';
modalTitle.textContent = featureName;
modalBody.innerHTML = '';
if (Object.keys(props).length === 0) {
modalBody.innerHTML = '<div class="modal-empty">No properties available</div>';
featureModal.classList.add('active');
return;
}
Object.entries(props).forEach(([key, value]) => {
const propDiv = document.createElement('div');
propDiv.className = 'modal-property';
const keyEl = document.createElement('div');
keyEl.className = 'modal-property-key';
keyEl.textContent = key;
const valueEl = document.createElement('div');
valueEl.className = 'modal-property-value';
valueEl.textContent = typeof value === 'object'
? JSON.stringify(value, null, 2)
: value;
propDiv.appendChild(keyEl);
propDiv.appendChild(valueEl);
modalBody.appendChild(propDiv);
});
featureModal.classList.add('active');
}
// Close feature modal
function closeFeatureModal() {
featureModal.classList.remove('active');
}
// Close modal when clicking outside
featureModal.addEventListener('click', (e) => {
if (e.target === featureModal) {
closeFeatureModal();
}
});
// Close modal with Escape key
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
closeFeatureModal();
}
});
// Clear all
clearBtn.addEventListener('click', () => {
if (confirm('Are you sure you want to clear all data?')) {
if (geojsonLayer) {
map.removeLayer(geojsonLayer);
geojsonLayer = null;
}
if (labelsLayer) {
map.removeLayer(labelsLayer);
labelsLayer = null;
}
currentGeojsonData = null;
featuresList = [];
geojsonInput.value = '';
fileNameDisplay.textContent = '';
fileNameDisplay.classList.remove('active');
summarySection.style.display = 'none';
statsSection.style.display = 'none';
tableSection.style.display = 'none';
featuresSection.style.display = 'none';
downloadBtn.style.display = 'none';
propertiesSection.classList.remove('active');
propertiesContent.innerHTML = '<div class="no-data">Select a feature to view properties</div>';
map.setView([0, 0], 2);
}
});
// Download
downloadBtn.addEventListener('click', () => {
if (!currentGeojsonData) return;
const dataStr = JSON.stringify(currentGeojsonData, null, 2);
const dataBlob = new Blob([dataStr], { type: 'application/json' });
const url = URL.createObjectURL(dataBlob);
const link = document.createElement('a');
link.href = url;
link.download = 'geojson-export.geojson';
link.click();
URL.revokeObjectURL(url);
showMessage('GeoJSON downloaded!', 'success');
});
// Search features
featureSearch.addEventListener('input', (e) => {
const searchTerm = e.target.value.toLowerCase();
const items = document.querySelectorAll('.feature-item');
items.forEach(item => {
const text = item.textContent.toLowerCase();
if (text.includes(searchTerm)) {
item.style.display = '';
} else {
item.style.display = 'none';
}
});
});
</script>
</body>
</html>