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
/**
* This code creates a geocoder widget similar to the Google Maps API search widget.
* It uses React for the frontend, the Cerebras API for LLM-based geocoding,
* and Leaflet for displaying the map.
*/
/** @jsxImportSource https://esm.sh/react */
import React, { useState, useEffect, useRef } from "https://esm.sh/react";
import { createRoot } from "https://esm.sh/react-dom/client";
import debounce from "https://esm.sh/lodash.debounce";
function App() {
const [query, setQuery] = useState("");
const [suggestions, setSuggestions] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [selectedLocation, setSelectedLocation] = useState(null);
const suggestionCache = useRef({});
const mapRef = useRef(null);
useEffect(() => {
if (typeof window !== "undefined") {
import("https://esm.sh/leaflet@1.9.4").then((L) => {
if (!mapRef.current) {
mapRef.current = L.map('map').setView([0, 0], 2);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(mapRef.current);
}
});
}
}, []);
useEffect(() => {
if (selectedLocation && mapRef.current) {
const { lat, lon } = selectedLocation;
mapRef.current.setView([lat, lon], 13);
L.marker([lat, lon]).addTo(mapRef.current);
}
}, [selectedLocation]);
const fetchSuggestions = async (input) => {
if (suggestionCache.current[input]) {
setSuggestions(suggestionCache.current[input]);
return;
}
setIsLoading(true);
try {
const response = await fetch("/geocode", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ query: input }),
});
if (!response.ok) throw new Error("Failed to fetch suggestions");
const data = await response.json();
setSuggestions(data);
suggestionCache.current[input] = data;
} catch (error) {
console.error("Error fetching suggestions:", error);
setSuggestions([]);
} finally {
setIsLoading(false);
}
};
const debouncedFetchSuggestions = useRef(
debounce(fetchSuggestions, 300)
).current;
useEffect(() => {
if (query.length > 2) {
debouncedFetchSuggestions(query);
} else {
setSuggestions([]);
}
}, [query]);
const handleSuggestionClick = (suggestion) => {
setQuery(suggestion.name);
setSelectedLocation({ lat: parseFloat(suggestion.latitude), lon: parseFloat(suggestion.longitude) });
setSuggestions([]);
};
return (
<div className="geocoder-container">
<div className="search-box">
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Enter a location"
/>
{isLoading && <div className="loader"></div>}
</div>
{suggestions.length > 0 && (
<ul className="suggestions">
{suggestions.map((suggestion, index) => (
<li key={index} onClick={() => handleSuggestionClick(suggestion)}>
<strong>{suggestion.name}</strong>
<br />