Spaces:
Running
Running
File size: 9,969 Bytes
1ed908c c3b3b4d 1ed908c c3b3b4d 1ed908c 7f390bd 1ed908c 32e860b 1ed908c 7f390bd 1ed908c 7f390bd 1ed908c 7f390bd 1ed908c 7f390bd 1ed908c f609be6 1ed908c 7f390bd 1ed908c c3b3b4d 1ed908c c3b3b4d 1ed908c 7f390bd 1ed908c 32e860b 1ed908c c3b3b4d 1ed908c c3b3b4d |
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 |
import { useEffect, useRef, useState } from 'react';
import maplibregl from 'maplibre-gl';
import 'maplibre-gl/dist/maplibre-gl.css';
import MaplibreDraw from 'maplibre-gl-draw';
import 'maplibre-gl-draw/dist/mapbox-gl-draw.css';
import { useGeoAIWorker } from './hooks/useGeoAIWorker';
import './App.css';
const config = {
provider: "esri",
serviceUrl: "https://server.arcgisonline.com/ArcGIS/rest/services",
serviceName: "World_Imagery",
tileSize: 256,
attribution: "ESRI World Imagery",
};
function App() {
const mapContainer = useRef(null);
const map = useRef(null);
const drawRef = useRef(null);
const [detections, setDetections] = useState([]);
const [currentPolygon, setCurrentPolygon] = useState(null);
const [isDrawing, setIsDrawing] = useState(false);
const [zoom, setZoom] = useState(null);
const [theme, setTheme] = useState(() => localStorage.getItem('theme') || 'light');
// when true we temporarily ignore any existing `result` from the worker (used after Clear)
const [suppressResult, setSuppressResult] = useState(false);
const { isReady, isProcessing, result, initialize, runInference } = useGeoAIWorker();
useEffect(() => {
localStorage.setItem('theme', theme);
}, [theme]);
const toggleTheme = () => setTheme(t => (t === 'light' ? 'dark' : 'light'));
useEffect(() => {
initialize([{ task: "building-detection" }], config);
}, []);
useEffect(() => {
if (!mapContainer.current) return;
map.current = new maplibregl.Map({
container: mapContainer.current,
style: {
version: 8,
sources: {
satellite: {
type: 'raster',
tiles: [
`https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}`,
],
tileSize: 256,
},
},
layers: [{ id: 'satellite', type: 'raster', source: 'satellite' }],
},
center: [-117.59, 47.653],
zoom: 18,
});
// set initial zoom state
setZoom(map.current.getZoom());
// update zoom on changes
const onZoom = () => setZoom(Number(map.current.getZoom().toFixed(2)));
map.current.on('zoom', onZoom);
const draw = new MaplibreDraw({
displayControlsDefault: false,
// don't render the default draw toolbar on the map; we'll control draw from the control panel
});
drawRef.current = draw;
// @ts-ignore
map.current.addControl(draw);
// cleanup map listeners on unmount
const cleanupMap = () => {
try {
map.current?.off('zoom', onZoom);
} catch (e) {}
};
map.current.on('draw.create', (e) => {
const polygon = e.features[0];
setCurrentPolygon(polygon);
// exit draw mode when a polygon is created
try { drawRef.current.changeMode('simple_select'); } catch (err) {}
setIsDrawing(false);
// DO NOT run inference automatically here. User must click Analyze.
});
map.current.on('draw.update', (e) => {
const polygon = e.features[0];
setCurrentPolygon(polygon);
});
map.current.on('draw.delete', (e) => {
setCurrentPolygon(null);
setDetections([]);
setIsDrawing(false);
// remove detections layer/source if present
if (map.current?.getSource('detections')) {
try {
map.current.removeLayer('detections');
map.current.removeSource('detections');
} catch (err) {}
}
});
return () => {
cleanupMap();
try {
// remove draw control if attached
if (map.current && drawRef.current) {
try { map.current.removeControl(drawRef.current); } catch (e) {}
}
map.current?.remove();
} catch (e) {}
// clear refs
map.current = null;
drawRef.current = null;
};
}, []); // initialize map once on mount; previously depended on isReady which caused the map to recreate when the worker became ready
useEffect(() => {
if (!result || suppressResult) return;
const features = result.detections?.features || [];
setDetections(features);
if (map.current?.getSource('detections')) {
map.current.removeLayer('detections');
map.current.removeSource('detections');
}
// set detection fill color to yellow
const fillColor = '#fdb306ff';
map.current?.addSource('detections', { type: 'geojson', data: result.detections });
map.current?.addLayer({
id: 'detections',
type: 'fill',
source: 'detections',
paint: { 'fill-color': fillColor, 'fill-opacity': 0.7 },
});
}, [result, theme]);
// manual analyze handler
const handleAnalyze = () => {
if (!isReady || !currentPolygon) return;
// allow the latest result to be shown again when user triggers analyze
setSuppressResult(false);
runInference({
inputs: { polygon: currentPolygon },
mapSourceParams: { zoomLevel: Math.round(map.current?.getZoom() || 18) },
});
};
// clear / reset everything on the map
const handleClear = () => {
// remove drawn shapes
if (drawRef.current) {
try { drawRef.current.deleteAll(); } catch (e) {}
}
// clear state
setCurrentPolygon(null);
setDetections([]);
// suppress previously computed result so it won't be re-applied to the map
setSuppressResult(true);
setIsDrawing(false);
// remove detections layer/source if present
try {
if (map.current?.getLayer('detections')) map.current.removeLayer('detections');
} catch (e) {}
try {
if (map.current?.getSource('detections')) map.current.removeSource('detections');
} catch (e) {}
// optionally fly back to initial view
try { map.current?.flyTo({ center: [-117.59, 47.653], zoom: 18 }); } catch (e) {}
};
const getDetectionsGeoJSON = () => result?.detections || null;
const handleCopy = async () => {
const geojson = getDetectionsGeoJSON();
if (!geojson) return;
try {
await navigator.clipboard.writeText(JSON.stringify(geojson, null, 2));
// optionally give feedback
} catch (err) {
console.error('Copy failed', err);
}
};
const handleDownload = () => {
const geojson = getDetectionsGeoJSON();
if (!geojson) return;
const blob = new Blob([JSON.stringify(geojson, null, 2)], { type: 'application/geo+json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'detections.geojson';
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
};
return (
<div className={`app-root ${theme === 'dark' ? 'theme-dark' : 'theme-light'}`}>
<header className="app-header">
<div className="brand">
<h1 className="brand-title">
GeoAI
<img src="https://cdn-icons-png.flaticon.com/256/5968/5968292.png" alt="JS logo" height="24" style={{ verticalAlign: 'middle', marginLeft: 8 }} />
</h1>
<div className="brand-text">
<h4 className="demo-title">Building Detection (Demo)</h4>
<p className="tagline">Inspect satellite imagery and detect buildings with GeoAI</p>
</div>
</div>
<div className="status">
<div className={`ready-dot ${isReady ? 'on' : 'off'}`}></div>
<span>{isReady ? 'Model ready' : 'Initializing...'}</span>
<button className="btn small" onClick={toggleTheme} style={{marginLeft:12}}>{theme === 'dark' ? 'Light' : 'Dark'}</button>
</div>
</header>
<main className="app-main">
<section className="map-area">
<div ref={mapContainer} className="map-container" />
</section>
<aside className="control-panel">
<h2>Controls</h2>
<p>Draw a polygon on the map to detect buildings in the selected area.</p>
<div className="controls-row">
<button className="btn" onClick={() => {
if (!drawRef.current) return;
try {
drawRef.current.changeMode('draw_polygon');
setIsDrawing(true);
} catch (err) { console.error(err); }
}} disabled={isDrawing || !isReady || isProcessing || Boolean(currentPolygon)}>
{isDrawing ? 'Drawing…' : 'Draw Polygon'}
</button>
<button className="btn" onClick={handleAnalyze} disabled={!currentPolygon || !isReady || isProcessing}>
{isProcessing ? 'Analyzing…' : 'Analyze'}
</button>
<button className="btn secondary" onClick={handleClear}>
Clear
</button>
</div>
<div className="stats">
<strong>{detections.length}</strong>
<span>Buildings found</span>
<div style={{marginLeft:12,color:'var(--muted)'}}>Zoom: {zoom !== null ? zoom : '—'}</div>
</div>
<div className="geojson-section">
<div className="geojson-header">
<h3>Detections GeoJSON</h3>
<div className="geojson-actions">
<button className="btn small" onClick={handleCopy} disabled={!result}>Copy</button>
<button className="btn small" onClick={handleDownload} disabled={!result}>Download</button>
</div>
</div>
<pre className="geojson-box" aria-live="polite">
{result ? JSON.stringify(result.detections, null, 2) : 'No detections yet.'}
</pre>
</div>
<div className="footer-note">
<a className="footer-link" href="https://geobase.app/" target="_blank" rel="noopener noreferrer">
<span><img width={15} src="/geobase-icon-tiny.svg" alt="Geobase small logo" className="footer-inline-logo" /> Geobase</span>
</a>
</div>
</aside>
</main>
</div>
);
}
export default App;
|