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";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useEffect, useRef, useState, useCallback } from "react";
|
||||
import maplibregl from "maplibre-gl";
|
||||
import "maplibre-gl/dist/maplibre-gl.css";
|
||||
import { Search, Loader2, MapPin, X } from "lucide-react";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
const STYLE_URL = "https://tiles.openfreemap.org/styles/bright";
|
||||
const TURKEY_CENTER: [number, number] = [35.0, 39.0];
|
||||
const MARKER_COLOR = "#2563eb";
|
||||
|
||||
interface NominatimResult {
|
||||
place_id: number;
|
||||
display_name: string;
|
||||
lat: string;
|
||||
lon: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
initialLat?: number | null;
|
||||
initialLng?: number | null;
|
||||
@@ -30,17 +36,20 @@ export function PropertyMapPickerInner({
|
||||
const mapRef = useRef<maplibregl.Map | null>(null);
|
||||
const markerRef = useRef<maplibregl.Marker | null>(null);
|
||||
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 [geocoding, setGeocoding] = useState(false);
|
||||
const [notFound, setNotFound] = useState(false);
|
||||
const [suggestions, setSuggestions] = useState<NominatimResult[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [showDropdown, setShowDropdown] = useState(false);
|
||||
const [coords, setCoords] = useState<{ lat: number; lng: number } | null>(
|
||||
initialLat != null && initialLng != null
|
||||
? { lat: initialLat, lng: initialLng }
|
||||
: 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) => {
|
||||
setCoords({ lat, lng });
|
||||
onLocationChange(lat, lng);
|
||||
@@ -61,6 +70,7 @@ export function PropertyMapPickerInner({
|
||||
}
|
||||
};
|
||||
|
||||
// Initialize map
|
||||
useEffect(() => {
|
||||
if (!containerRef.current) return;
|
||||
|
||||
@@ -106,75 +116,127 @@ export function PropertyMapPickerInner({
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
async function handleSearch(e?: React.FormEvent) {
|
||||
e?.preventDefault();
|
||||
if (!search.trim()) return;
|
||||
setGeocoding(true);
|
||||
setNotFound(false);
|
||||
// Close dropdown when clicking outside
|
||||
useEffect(() => {
|
||||
function handleClickOutside(e: MouseEvent) {
|
||||
if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
|
||||
setShowDropdown(false);
|
||||
}
|
||||
}
|
||||
document.addEventListener("mousedown", handleClickOutside);
|
||||
return () => document.removeEventListener("mousedown", handleClickOutside);
|
||||
}, []);
|
||||
|
||||
try {
|
||||
const q = search.includes("Türkiye") ? search : `${search}, Türkiye`;
|
||||
const res = await fetch(
|
||||
`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(q)}&format=json&limit=1`,
|
||||
{ headers: { "Accept-Language": "tr,en" } },
|
||||
);
|
||||
const data = (await res.json()) as { lat: string; lon: string }[];
|
||||
|
||||
if (!data.length) {
|
||||
setNotFound(true);
|
||||
// Debounced Nominatim fetch
|
||||
const fetchSuggestions = useCallback(async (query: string) => {
|
||||
if (!query.trim() || query.trim().length < 3) {
|
||||
setSuggestions([]);
|
||||
setShowDropdown(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const lat = parseFloat(data[0].lat);
|
||||
const lng = parseFloat(data[0].lon);
|
||||
setLoading(true);
|
||||
try {
|
||||
const q = query.includes("Türkiye") ? query : `${query}, Türkiye`;
|
||||
const res = await fetch(
|
||||
`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(q)}&format=json&limit=6&addressdetails=0`,
|
||||
{ headers: { "Accept-Language": "tr,en" } },
|
||||
);
|
||||
const data = (await res.json()) as NominatimResult[];
|
||||
setSuggestions(data);
|
||||
setShowDropdown(data.length > 0);
|
||||
} catch {
|
||||
setSuggestions([]);
|
||||
setShowDropdown(false);
|
||||
} finally {
|
||||
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: 1000 });
|
||||
} catch {
|
||||
setNotFound(true);
|
||||
} finally {
|
||||
setGeocoding(false);
|
||||
}
|
||||
mapRef.current?.flyTo({ center: [lng, lat], zoom: 15, duration: 900 });
|
||||
}
|
||||
|
||||
function handleClear() {
|
||||
markerRef.current?.remove();
|
||||
markerRef.current = null;
|
||||
setCoords(null);
|
||||
setSearch("");
|
||||
setSuggestions([]);
|
||||
setShowDropdown(false);
|
||||
onClear();
|
||||
mapRef.current?.flyTo({ center: TURKEY_CENTER, zoom: 5.5 });
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{/* Search bar */}
|
||||
<form onSubmit={handleSearch} className="flex gap-2">
|
||||
<div className="relative flex-1">
|
||||
{/* Search input with autocomplete dropdown */}
|
||||
<div className="relative" ref={dropdownRef}>
|
||||
<div className="relative">
|
||||
<Search className="text-muted-foreground absolute left-2.5 top-2.5 size-4" />
|
||||
<Input
|
||||
className="pl-8"
|
||||
className="pl-8 pr-8"
|
||||
placeholder="Adres, mahalle veya şehir ara..."
|
||||
value={search}
|
||||
onChange={(e) => {
|
||||
setSearch(e.target.value);
|
||||
setNotFound(false);
|
||||
}}
|
||||
autoComplete="off"
|
||||
onChange={(e) => handleInputChange(e.target.value)}
|
||||
onFocus={() => suggestions.length > 0 && setShowDropdown(true)}
|
||||
/>
|
||||
{loading && (
|
||||
<Loader2 className="text-muted-foreground absolute right-2.5 top-2.5 size-4 animate-spin" />
|
||||
)}
|
||||
</div>
|
||||
<Button type="submit" variant="outline" size="icon" disabled={geocoding}>
|
||||
{geocoding ? (
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
) : (
|
||||
<Search className="size-4" />
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{notFound && (
|
||||
<p className="text-destructive text-xs">
|
||||
Adres bulunamadı — farklı bir arama deneyin.
|
||||
</p>
|
||||
{showDropdown && suggestions.length > 0 && (
|
||||
<div className="absolute z-50 mt-1 w-full rounded-md border bg-popover shadow-md">
|
||||
<ul className="py-1 text-sm">
|
||||
{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 */}
|
||||
<div
|
||||
|
||||
Reference in New Issue
Block a user