feat: harita adres araması autocomplete dropdown'a dönüştürüldü
- 3 karakter sonrası 400ms debounce ile Nominatim'den öneri çeker - Yükleniyor spinner input sağında - Dropdown: MapPin + tam adres, onMouseDown ile blur çakışması önlendi - Seçim sonrası kısa isim input'a yazılır, harita flyTo ile konuma gider - Dışarı tıklanınca dropdown kapanır
This commit is contained in:
@@ -1,16 +1,22 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState, useCallback } from "react";
|
||||||
import maplibregl from "maplibre-gl";
|
import maplibregl from "maplibre-gl";
|
||||||
import "maplibre-gl/dist/maplibre-gl.css";
|
import "maplibre-gl/dist/maplibre-gl.css";
|
||||||
import { Search, Loader2, MapPin, X } from "lucide-react";
|
import { Search, Loader2, MapPin, X } from "lucide-react";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
|
|
||||||
const STYLE_URL = "https://tiles.openfreemap.org/styles/bright";
|
const STYLE_URL = "https://tiles.openfreemap.org/styles/bright";
|
||||||
const TURKEY_CENTER: [number, number] = [35.0, 39.0];
|
const TURKEY_CENTER: [number, number] = [35.0, 39.0];
|
||||||
const MARKER_COLOR = "#2563eb";
|
const MARKER_COLOR = "#2563eb";
|
||||||
|
|
||||||
|
interface NominatimResult {
|
||||||
|
place_id: number;
|
||||||
|
display_name: string;
|
||||||
|
lat: string;
|
||||||
|
lon: string;
|
||||||
|
}
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
initialLat?: number | null;
|
initialLat?: number | null;
|
||||||
initialLng?: number | null;
|
initialLng?: number | null;
|
||||||
@@ -30,17 +36,20 @@ export function PropertyMapPickerInner({
|
|||||||
const mapRef = useRef<maplibregl.Map | null>(null);
|
const mapRef = useRef<maplibregl.Map | null>(null);
|
||||||
const markerRef = useRef<maplibregl.Marker | null>(null);
|
const markerRef = useRef<maplibregl.Marker | null>(null);
|
||||||
const placeRef = useRef<(lat: number, lng: number) => void>(() => {});
|
const placeRef = useRef<(lat: number, lng: number) => void>(() => {});
|
||||||
|
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
|
const dropdownRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
const [search, setSearch] = useState(initialSearchQuery);
|
const [search, setSearch] = useState(initialSearchQuery);
|
||||||
const [geocoding, setGeocoding] = useState(false);
|
const [suggestions, setSuggestions] = useState<NominatimResult[]>([]);
|
||||||
const [notFound, setNotFound] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [showDropdown, setShowDropdown] = useState(false);
|
||||||
const [coords, setCoords] = useState<{ lat: number; lng: number } | null>(
|
const [coords, setCoords] = useState<{ lat: number; lng: number } | null>(
|
||||||
initialLat != null && initialLng != null
|
initialLat != null && initialLng != null
|
||||||
? { lat: initialLat, lng: initialLng }
|
? { lat: initialLat, lng: initialLng }
|
||||||
: null,
|
: null,
|
||||||
);
|
);
|
||||||
|
|
||||||
// Keep placeRef current so closures in event handlers always have latest state
|
// Keep placeRef current so closures in map event handlers see latest callbacks
|
||||||
placeRef.current = (lat: number, lng: number) => {
|
placeRef.current = (lat: number, lng: number) => {
|
||||||
setCoords({ lat, lng });
|
setCoords({ lat, lng });
|
||||||
onLocationChange(lat, lng);
|
onLocationChange(lat, lng);
|
||||||
@@ -61,6 +70,7 @@ export function PropertyMapPickerInner({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Initialize map
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!containerRef.current) return;
|
if (!containerRef.current) return;
|
||||||
|
|
||||||
@@ -106,75 +116,127 @@ export function PropertyMapPickerInner({
|
|||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
async function handleSearch(e?: React.FormEvent) {
|
// Close dropdown when clicking outside
|
||||||
e?.preventDefault();
|
useEffect(() => {
|
||||||
if (!search.trim()) return;
|
function handleClickOutside(e: MouseEvent) {
|
||||||
setGeocoding(true);
|
if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
|
||||||
setNotFound(false);
|
setShowDropdown(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
document.addEventListener("mousedown", handleClickOutside);
|
||||||
|
return () => document.removeEventListener("mousedown", handleClickOutside);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Debounced Nominatim fetch
|
||||||
|
const fetchSuggestions = useCallback(async (query: string) => {
|
||||||
|
if (!query.trim() || query.trim().length < 3) {
|
||||||
|
setSuggestions([]);
|
||||||
|
setShowDropdown(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const q = search.includes("Türkiye") ? search : `${search}, Türkiye`;
|
const q = query.includes("Türkiye") ? query : `${query}, Türkiye`;
|
||||||
const res = await fetch(
|
const res = await fetch(
|
||||||
`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(q)}&format=json&limit=1`,
|
`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(q)}&format=json&limit=6&addressdetails=0`,
|
||||||
{ headers: { "Accept-Language": "tr,en" } },
|
{ headers: { "Accept-Language": "tr,en" } },
|
||||||
);
|
);
|
||||||
const data = (await res.json()) as { lat: string; lon: string }[];
|
const data = (await res.json()) as NominatimResult[];
|
||||||
|
setSuggestions(data);
|
||||||
if (!data.length) {
|
setShowDropdown(data.length > 0);
|
||||||
setNotFound(true);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const lat = parseFloat(data[0].lat);
|
|
||||||
const lng = parseFloat(data[0].lon);
|
|
||||||
|
|
||||||
placeRef.current(lat, lng);
|
|
||||||
mapRef.current?.flyTo({ center: [lng, lat], zoom: 15, duration: 1000 });
|
|
||||||
} catch {
|
} catch {
|
||||||
setNotFound(true);
|
setSuggestions([]);
|
||||||
|
setShowDropdown(false);
|
||||||
} finally {
|
} finally {
|
||||||
setGeocoding(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
function handleInputChange(value: string) {
|
||||||
|
setSearch(value);
|
||||||
|
|
||||||
|
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||||
|
|
||||||
|
if (value.trim().length < 3) {
|
||||||
|
setSuggestions([]);
|
||||||
|
setShowDropdown(false);
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoading(true);
|
||||||
|
debounceRef.current = setTimeout(() => {
|
||||||
|
void fetchSuggestions(value);
|
||||||
|
}, 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleSelect(result: NominatimResult) {
|
||||||
|
const lat = parseFloat(result.lat);
|
||||||
|
const lng = parseFloat(result.lon);
|
||||||
|
|
||||||
|
// Shorten display_name for the search box (first two parts)
|
||||||
|
const short = result.display_name.split(",").slice(0, 2).join(",").trim();
|
||||||
|
setSearch(short);
|
||||||
|
setSuggestions([]);
|
||||||
|
setShowDropdown(false);
|
||||||
|
|
||||||
|
placeRef.current(lat, lng);
|
||||||
|
mapRef.current?.flyTo({ center: [lng, lat], zoom: 15, duration: 900 });
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleClear() {
|
function handleClear() {
|
||||||
markerRef.current?.remove();
|
markerRef.current?.remove();
|
||||||
markerRef.current = null;
|
markerRef.current = null;
|
||||||
setCoords(null);
|
setCoords(null);
|
||||||
|
setSearch("");
|
||||||
|
setSuggestions([]);
|
||||||
|
setShowDropdown(false);
|
||||||
onClear();
|
onClear();
|
||||||
mapRef.current?.flyTo({ center: TURKEY_CENTER, zoom: 5.5 });
|
mapRef.current?.flyTo({ center: TURKEY_CENTER, zoom: 5.5 });
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
{/* Search bar */}
|
{/* Search input with autocomplete dropdown */}
|
||||||
<form onSubmit={handleSearch} className="flex gap-2">
|
<div className="relative" ref={dropdownRef}>
|
||||||
<div className="relative flex-1">
|
<div className="relative">
|
||||||
<Search className="text-muted-foreground absolute left-2.5 top-2.5 size-4" />
|
<Search className="text-muted-foreground absolute left-2.5 top-2.5 size-4" />
|
||||||
<Input
|
<Input
|
||||||
className="pl-8"
|
className="pl-8 pr-8"
|
||||||
placeholder="Adres, mahalle veya şehir ara..."
|
placeholder="Adres, mahalle veya şehir ara..."
|
||||||
value={search}
|
value={search}
|
||||||
onChange={(e) => {
|
autoComplete="off"
|
||||||
setSearch(e.target.value);
|
onChange={(e) => handleInputChange(e.target.value)}
|
||||||
setNotFound(false);
|
onFocus={() => suggestions.length > 0 && setShowDropdown(true)}
|
||||||
}}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
{loading && (
|
||||||
<Button type="submit" variant="outline" size="icon" disabled={geocoding}>
|
<Loader2 className="text-muted-foreground absolute right-2.5 top-2.5 size-4 animate-spin" />
|
||||||
{geocoding ? (
|
|
||||||
<Loader2 className="size-4 animate-spin" />
|
|
||||||
) : (
|
|
||||||
<Search className="size-4" />
|
|
||||||
)}
|
)}
|
||||||
</Button>
|
</div>
|
||||||
</form>
|
|
||||||
|
|
||||||
{notFound && (
|
{showDropdown && suggestions.length > 0 && (
|
||||||
<p className="text-destructive text-xs">
|
<div className="absolute z-50 mt-1 w-full rounded-md border bg-popover shadow-md">
|
||||||
Adres bulunamadı — farklı bir arama deneyin.
|
<ul className="py-1 text-sm">
|
||||||
</p>
|
{suggestions.map((s) => (
|
||||||
)}
|
<li key={s.place_id}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="flex w-full items-start gap-2 px-3 py-2 text-left hover:bg-accent hover:text-accent-foreground"
|
||||||
|
onMouseDown={(e) => {
|
||||||
|
e.preventDefault(); // prevent input blur before click registers
|
||||||
|
handleSelect(s);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<MapPin className="mt-0.5 size-3.5 shrink-0 text-muted-foreground" />
|
||||||
|
<span className="line-clamp-2 leading-snug">{s.display_name}</span>
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Map */}
|
{/* Map */}
|
||||||
<div
|
<div
|
||||||
|
|||||||
Reference in New Issue
Block a user