Ben Mitchinson 2 days ago committed by GitHub
commit 898b6b52f4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -37,6 +37,16 @@ const LocationMarker = (props: MarkerProps) => {
map.locate(); map.locate();
}, []); }, []);
// Keep marker and map in sync with external position updates
useEffect(() => {
if (props.position) {
setPosition(props.position);
map.setView(props.position);
} else {
setPosition(undefined);
}
}, [props.position, map]);
return position === undefined ? null : <Marker position={position} icon={markerIcon}></Marker>; return position === undefined ? null : <Marker position={position} icon={markerIcon}></Marker>;
}; };

@ -16,17 +16,21 @@ interface Props {
} }
interface State { interface State {
initilized: boolean; initialized: boolean;
placeholder: string; placeholder: string;
position?: LatLng; position?: LatLng;
latInput: string;
lngInput: string;
} }
const LocationSelector = (props: Props) => { const LocationSelector = (props: Props) => {
const t = useTranslate(); const t = useTranslate();
const [state, setState] = useState<State>({ const [state, setState] = useState<State>({
initilized: false, initialized: false,
placeholder: props.location?.placeholder || "", placeholder: props.location?.placeholder || "",
position: props.location ? new LatLng(props.location.latitude, props.location.longitude) : undefined, position: props.location ? new LatLng(props.location.latitude, props.location.longitude) : undefined,
latInput: props.location ? String(props.location.latitude) : "",
lngInput: props.location ? String(props.location.longitude) : "",
}); });
const [popoverOpen, setPopoverOpen] = useState<boolean>(false); const [popoverOpen, setPopoverOpen] = useState<boolean>(false);
@ -35,13 +39,15 @@ const LocationSelector = (props: Props) => {
...state, ...state,
placeholder: props.location?.placeholder || "", placeholder: props.location?.placeholder || "",
position: new LatLng(props.location?.latitude || 0, props.location?.longitude || 0), position: new LatLng(props.location?.latitude || 0, props.location?.longitude || 0),
latInput: String(props.location?.latitude) || "",
lngInput: String(props.location?.longitude) || "",
})); }));
}, [props.location]); }, [props.location]);
useEffect(() => { useEffect(() => {
if (popoverOpen && !props.location) { if (popoverOpen && !props.location) {
const handleError = (error: any, errorMessage: string) => { const handleError = (error: any, errorMessage: string) => {
setState({ ...state, initilized: true }); setState({ ...state, initialized: true });
toast.error(errorMessage); toast.error(errorMessage);
console.error(error); console.error(error);
}; };
@ -51,7 +57,7 @@ const LocationSelector = (props: Props) => {
(position) => { (position) => {
const lat = position.coords.latitude; const lat = position.coords.latitude;
const lng = position.coords.longitude; const lng = position.coords.longitude;
setState({ ...state, position: new LatLng(lat, lng), initilized: true }); setState({ ...state, position: new LatLng(lat, lng), initialized: true });
}, },
(error) => { (error) => {
handleError(error, "Failed to get current position"); handleError(error, "Failed to get current position");
@ -65,16 +71,23 @@ const LocationSelector = (props: Props) => {
useEffect(() => { useEffect(() => {
if (!state.position) { if (!state.position) {
setState({ ...state, placeholder: "" }); setState((prev) => ({ ...prev, placeholder: "" }));
return; return;
} }
// Sync lat/lng input values from position
const newLat = String(state.position.lat);
const newLng = String(state.position.lng);
if (state.latInput !== newLat || state.lngInput !== newLng) {
setState((prev) => ({ ...prev, latInput: newLat, lngInput: newLng }));
}
// Fetch reverse geocoding data. // Fetch reverse geocoding data.
fetch(`https://nominatim.openstreetmap.org/reverse?lat=${state.position.lat}&lon=${state.position.lng}&format=json`) fetch(`https://nominatim.openstreetmap.org/reverse?lat=${state.position.lat}&lon=${state.position.lng}&format=json`)
.then((response) => response.json()) .then((response) => response.json())
.then((data) => { .then((data) => {
if (data && data.display_name) { if (data && data.display_name) {
setState({ ...state, placeholder: data.display_name }); setState((prev) => ({ ...prev, placeholder: data.display_name }));
} }
}) })
.catch((error) => { .catch((error) => {
@ -83,8 +96,19 @@ const LocationSelector = (props: Props) => {
}); });
}, [state.position]); }, [state.position]);
// Update position when lat/lng inputs change (if valid numbers)
useEffect(() => {
const lat = parseFloat(state.latInput);
const lng = parseFloat(state.lngInput);
if (Number.isFinite(lat) && Number.isFinite(lng)) {
if (!state.position || state.position.lat !== lat || state.position.lng !== lng) {
setState((prev) => ({ ...prev, position: new LatLng(lat, lng) }));
}
}
}, [state.latInput, state.lngInput]);
const onPositionChanged = (position: LatLng) => { const onPositionChanged = (position: LatLng) => {
setState({ ...state, position }); setState((prev) => ({ ...prev, position }));
}; };
const removeLocation = (e: React.MouseEvent) => { const removeLocation = (e: React.MouseEvent) => {
@ -123,22 +147,34 @@ const LocationSelector = (props: Props) => {
</TooltipProvider> </TooltipProvider>
<PopoverContent align="center"> <PopoverContent align="center">
<div className="min-w-80 sm:w-lg p-1 flex flex-col justify-start items-start"> <div className="min-w-80 sm:w-lg p-1 flex flex-col justify-start items-start">
<LeafletMap key={JSON.stringify(state.initilized)} latlng={state.position} onChange={onPositionChanged} /> <LeafletMap key={JSON.stringify(state.initialized)} latlng={state.position} onChange={onPositionChanged} />
<div className="mt-2 w-full flex flex-row justify-between items-center gap-2"> <div className="mt-2 w-full flex flex-row justify-between items-center gap-2">
<div className="flex flex-row items-center justify-start gap-2 w-full"> <div className="flex flex-row items-center justify-start gap-2 w-full">
<div className="relative flex-1"> <div id="lat-long-display" className="flex flex-row items-center gap-2">
{state.position && ( <Input
<div className="absolute left-2 top-1/2 -translate-y-1/2 text-xs leading-6 opacity-60 z-10"> placeholder="Lat"
[{state.position.lat.toFixed(2)}, {state.position.lng.toFixed(2)}] type="number"
</div> step="any"
)} value={state.latInput}
onChange={(e) => setState((prev) => ({ ...prev, latInput: e.target.value }))}
className="w-28"
/>
<Input <Input
placeholder="Choose a position first." placeholder="Lng"
value={state.placeholder} type="number"
disabled={!state.position} step="any"
className={state.position ? "pl-24" : ""} value={state.lngInput}
onChange={(e) => setState((state) => ({ ...state, placeholder: e.target.value }))} onChange={(e) => setState((prev) => ({ ...prev, lngInput: e.target.value }))}
className="w-28"
/> />
<div className="relative flex-1">
<Input
placeholder="Choose a position first."
value={state.placeholder}
disabled={!state.position}
onChange={(e) => setState((prev) => ({ ...prev, placeholder: e.target.value }))}
/>
</div>
</div> </div>
</div> </div>
<Button <Button

Loading…
Cancel
Save