feat(web): add listing detail page and Mapbox GL JS map integration
- Create public listing detail page at /listings/[id] with image gallery, property specs, contact card, and embedded map - Rewrite ListingMap component to use Mapbox GL JS with interactive markers, price labels, and listing popups - Add selectedListingId prop to search page map views for marker highlighting - Install mapbox-gl dependency Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
333
apps/web/app/(public)/listings/[id]/page.tsx
Normal file
333
apps/web/app/(public)/listings/[id]/page.tsx
Normal file
@@ -0,0 +1,333 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useParams } from 'next/navigation';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { ImageGallery } from '@/components/listings/image-gallery';
|
||||
import { ListingMap } from '@/components/map/listing-map';
|
||||
import { listingsApi, type ListingDetail } from '@/lib/listings-api';
|
||||
import { PROPERTY_TYPES, DIRECTIONS, TRANSACTION_TYPES } from '@/lib/validations/listings';
|
||||
|
||||
function formatPrice(priceVND: string): string {
|
||||
const num = Number(priceVND);
|
||||
if (num >= 1_000_000_000) return `${(num / 1_000_000_000).toFixed(1)} tỷ`;
|
||||
if (num >= 1_000_000) return `${(num / 1_000_000).toFixed(0)} triệu`;
|
||||
return num.toLocaleString('vi-VN');
|
||||
}
|
||||
|
||||
function getLabel(list: readonly { value: string; label: string }[], value: string | null) {
|
||||
if (!value) return null;
|
||||
return list.find((item) => item.value === value)?.label ?? value;
|
||||
}
|
||||
|
||||
export default function PublicListingDetailPage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const [listing, setListing] = React.useState<ListingDetail | null>(null);
|
||||
const [loading, setLoading] = React.useState(true);
|
||||
const [error, setError] = React.useState<string | null>(null);
|
||||
|
||||
React.useEffect(() => {
|
||||
listingsApi
|
||||
.getById(id)
|
||||
.then(setListing)
|
||||
.catch((err) => setError(err instanceof Error ? err.message : 'Khong tai duoc tin dang'))
|
||||
.finally(() => setLoading(false));
|
||||
}, [id]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="mx-auto max-w-6xl px-4 py-8">
|
||||
{/* Skeleton loader */}
|
||||
<div className="animate-pulse space-y-6">
|
||||
<div className="h-8 w-2/3 rounded bg-muted" />
|
||||
<div className="aspect-video rounded-lg bg-muted" />
|
||||
<div className="grid gap-6 lg:grid-cols-3">
|
||||
<div className="space-y-4 lg:col-span-2">
|
||||
<div className="h-40 rounded-lg bg-muted" />
|
||||
<div className="h-32 rounded-lg bg-muted" />
|
||||
</div>
|
||||
<div className="h-48 rounded-lg bg-muted" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error || !listing) {
|
||||
return (
|
||||
<div className="flex min-h-[400px] flex-col items-center justify-center space-y-4">
|
||||
<svg className="h-12 w-12 text-muted-foreground" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
|
||||
</svg>
|
||||
<p className="text-destructive">{error || 'Khong tim thay tin dang'}</p>
|
||||
<Link href="/search">
|
||||
<Button variant="outline">Quay lai tim kiem</Button>
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const { property, seller, agent } = listing;
|
||||
const transactionLabel = getLabel(TRANSACTION_TYPES, listing.transactionType);
|
||||
const propertyTypeLabel = getLabel(PROPERTY_TYPES, property.propertyType);
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-6xl px-4 py-6">
|
||||
{/* Breadcrumb */}
|
||||
<nav className="mb-4 flex items-center gap-1.5 text-sm text-muted-foreground">
|
||||
<Link href="/" className="hover:text-foreground">Trang chu</Link>
|
||||
<span>/</span>
|
||||
<Link href="/search" className="hover:text-foreground">Tim kiem</Link>
|
||||
<span>/</span>
|
||||
<span className="truncate text-foreground">{property.title}</span>
|
||||
</nav>
|
||||
|
||||
{/* Header */}
|
||||
<div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="mb-2 flex flex-wrap items-center gap-2">
|
||||
{transactionLabel && (
|
||||
<Badge variant={listing.transactionType === 'SALE' ? 'default' : 'secondary'}>
|
||||
{transactionLabel}
|
||||
</Badge>
|
||||
)}
|
||||
{propertyTypeLabel && <Badge variant="outline">{propertyTypeLabel}</Badge>}
|
||||
</div>
|
||||
<h1 className="text-2xl font-bold md:text-3xl">{property.title}</h1>
|
||||
<p className="mt-1 flex items-center gap-1 text-muted-foreground">
|
||||
<svg className="h-4 w-4 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
</svg>
|
||||
{property.address}, {property.ward}, {property.district}, {property.city}
|
||||
</p>
|
||||
</div>
|
||||
<div className="shrink-0 text-right">
|
||||
<p className="text-2xl font-bold text-primary md:text-3xl">{formatPrice(listing.priceVND)} VND</p>
|
||||
{listing.pricePerM2 != null && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
~{listing.pricePerM2.toLocaleString('vi-VN')} VND/m2
|
||||
</p>
|
||||
)}
|
||||
{listing.rentPriceMonthly && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Thue: {formatPrice(listing.rentPriceMonthly)}/thang
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Image gallery */}
|
||||
<ImageGallery media={property.media} />
|
||||
|
||||
{/* Quick specs bar */}
|
||||
<div className="my-6 flex flex-wrap gap-4 rounded-lg border bg-card p-4">
|
||||
<QuickStat icon="area" label="Dien tich" value={`${property.areaM2} m\u00B2`} />
|
||||
{property.bedrooms != null && (
|
||||
<QuickStat icon="bed" label="Phong ngu" value={`${property.bedrooms}`} />
|
||||
)}
|
||||
{property.bathrooms != null && (
|
||||
<QuickStat icon="bath" label="Phong tam" value={`${property.bathrooms}`} />
|
||||
)}
|
||||
{property.floors != null && (
|
||||
<QuickStat icon="floors" label="So tang" value={`${property.floors}`} />
|
||||
)}
|
||||
{property.direction && (
|
||||
<QuickStat icon="compass" label="Huong" value={getLabel(DIRECTIONS, property.direction) || ''} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 lg:grid-cols-3">
|
||||
{/* Main content */}
|
||||
<div className="space-y-6 lg:col-span-2">
|
||||
{/* Description */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Mo ta</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="whitespace-pre-wrap text-sm leading-relaxed">{property.description}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Details */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Thong tin chi tiet</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3">
|
||||
<InfoItem label="Loai BDS" value={propertyTypeLabel || '---'} />
|
||||
<InfoItem label="Dien tich" value={`${property.areaM2} m\u00B2`} />
|
||||
<InfoItem label="Phong ngu" value={property.bedrooms != null ? `${property.bedrooms}` : '---'} />
|
||||
<InfoItem label="Phong tam" value={property.bathrooms != null ? `${property.bathrooms}` : '---'} />
|
||||
<InfoItem label="So tang" value={property.floors != null ? `${property.floors}` : '---'} />
|
||||
<InfoItem label="Huong" value={getLabel(DIRECTIONS, property.direction) || '---'} />
|
||||
<InfoItem label="Nam xay" value={property.yearBuilt ? `${property.yearBuilt}` : '---'} />
|
||||
<InfoItem label="Phap ly" value={property.legalStatus || '---'} />
|
||||
<InfoItem label="Du an" value={property.projectName || '---'} />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Amenities */}
|
||||
{property.amenities && property.amenities.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Tien ich</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{property.amenities.map((a) => (
|
||||
<Badge key={a} variant="secondary">
|
||||
{a}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Map */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Vi tri tren ban do</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ListingMap
|
||||
listings={[listing]}
|
||||
className="h-[300px]"
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Sidebar */}
|
||||
<div className="space-y-6">
|
||||
{/* Contact card */}
|
||||
<Card className="sticky top-20">
|
||||
<CardHeader>
|
||||
<CardTitle>Lien he</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/10 text-primary">
|
||||
<svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">{seller.fullName}</p>
|
||||
<p className="text-sm text-muted-foreground">{seller.phone}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<a href={`tel:${seller.phone}`}>
|
||||
<Button className="w-full gap-2">
|
||||
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
|
||||
</svg>
|
||||
Goi ngay
|
||||
</Button>
|
||||
</a>
|
||||
<Button variant="outline" className="w-full gap-2">
|
||||
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
|
||||
</svg>
|
||||
Nhan tin
|
||||
</Button>
|
||||
|
||||
{agent && (
|
||||
<div className="border-t pt-3">
|
||||
<p className="text-xs text-muted-foreground">Moi gioi</p>
|
||||
{agent.agency && <p className="text-sm font-medium">{agent.agency}</p>}
|
||||
{listing.commissionPct != null && (
|
||||
<p className="text-xs text-muted-foreground">Hoa hong: {listing.commissionPct}%</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Stats */}
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="grid grid-cols-3 gap-4 text-center">
|
||||
<div>
|
||||
<p className="text-lg font-bold">{listing.viewCount}</p>
|
||||
<p className="text-xs text-muted-foreground">Luot xem</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-lg font-bold">{listing.saveCount}</p>
|
||||
<p className="text-xs text-muted-foreground">Luot luu</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-lg font-bold">{listing.inquiryCount}</p>
|
||||
<p className="text-xs text-muted-foreground">Lien he</p>
|
||||
</div>
|
||||
</div>
|
||||
{listing.publishedAt && (
|
||||
<p className="mt-3 border-t pt-3 text-center text-xs text-muted-foreground">
|
||||
Dang ngay {new Date(listing.publishedAt).toLocaleDateString('vi-VN')}
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function QuickStat({ icon, label, value }: { icon: string; label: string; value: string }) {
|
||||
const icons: Record<string, React.ReactNode> = {
|
||||
area: (
|
||||
<svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4" />
|
||||
</svg>
|
||||
),
|
||||
bed: (
|
||||
<svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M3 7v11m0-7h18M3 18h18M6 14h.01M6 10a2 2 0 012-2h8a2 2 0 012 2v0H6z" />
|
||||
</svg>
|
||||
),
|
||||
bath: (
|
||||
<svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M4 12h16M4 12a2 2 0 00-2 2v2a4 4 0 004 4h12a4 4 0 004-4v-2a2 2 0 00-2-2M4 12V7a3 3 0 013-3h1" />
|
||||
</svg>
|
||||
),
|
||||
floors: (
|
||||
<svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
|
||||
</svg>
|
||||
),
|
||||
compass: (
|
||||
<svg className="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 9l3 3m0 0l3-3m-3 3V6m0 6l-3 3m3-3l3 3m-3-3v6" />
|
||||
</svg>
|
||||
),
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="text-muted-foreground">{icons[icon]}</div>
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground">{label}</p>
|
||||
<p className="text-sm font-semibold">{value}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function InfoItem({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div>
|
||||
<p className="text-xs text-muted-foreground">{label}</p>
|
||||
<p className="font-medium">{value}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -44,6 +44,11 @@ function SearchContent() {
|
||||
const [loading, setLoading] = React.useState(true);
|
||||
const [viewMode, setViewMode] = React.useState<ViewMode>('list');
|
||||
const [showMobileFilters, setShowMobileFilters] = React.useState(false);
|
||||
const [selectedListingId, setSelectedListingId] = React.useState<string | undefined>();
|
||||
|
||||
const handleMarkerClick = (listing: ListingDetail) => {
|
||||
setSelectedListingId(listing.id);
|
||||
};
|
||||
|
||||
const fetchListings = React.useCallback(() => {
|
||||
setLoading(true);
|
||||
@@ -219,6 +224,8 @@ function SearchContent() {
|
||||
{viewMode === 'map' && (
|
||||
<ListingMap
|
||||
listings={result?.data || []}
|
||||
selectedListingId={selectedListingId}
|
||||
onMarkerClick={handleMarkerClick}
|
||||
className="h-[calc(100vh-220px)]"
|
||||
/>
|
||||
)}
|
||||
@@ -238,6 +245,8 @@ function SearchContent() {
|
||||
<div className="hidden lg:block">
|
||||
<ListingMap
|
||||
listings={result?.data || []}
|
||||
selectedListingId={selectedListingId}
|
||||
onMarkerClick={handleMarkerClick}
|
||||
className="sticky top-20 h-[calc(100vh-220px)]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
import mapboxgl from 'mapbox-gl';
|
||||
import 'mapbox-gl/dist/mapbox-gl.css';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import type { ListingDetail } from '@/lib/listings-api';
|
||||
|
||||
function formatPrice(priceVND: string): string {
|
||||
@@ -15,6 +16,7 @@ function formatPrice(priceVND: string): string {
|
||||
interface ListingMapProps {
|
||||
listings: ListingDetail[];
|
||||
onMarkerClick?: (listing: ListingDetail) => void;
|
||||
selectedListingId?: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
@@ -24,160 +26,203 @@ interface MapMarker {
|
||||
lng: number;
|
||||
}
|
||||
|
||||
export function ListingMap({ listings, onMarkerClick, className }: ListingMapProps) {
|
||||
const [selectedMarker, setSelectedMarker] = React.useState<MapMarker | null>(null);
|
||||
const mapRef = React.useRef<HTMLDivElement>(null);
|
||||
const CITY_COORDS: Record<string, [number, number]> = {
|
||||
'Hồ Chí Minh': [10.8231, 106.6297],
|
||||
'Hà Nội': [21.0285, 105.8542],
|
||||
'Đà Nẵng': [16.0544, 108.2022],
|
||||
'Nha Trang': [12.2388, 109.1967],
|
||||
'Cần Thơ': [10.0452, 105.7469],
|
||||
};
|
||||
|
||||
// Parse listings with valid coordinates
|
||||
const markers = React.useMemo(() => {
|
||||
return listings
|
||||
.filter((l) => {
|
||||
// ListingDetail doesn't expose lat/lng directly, but the property might have it
|
||||
// For now we'll use a simple city-based mapping as fallback
|
||||
return true;
|
||||
})
|
||||
.map((listing, index) => {
|
||||
// Generate approximate coordinates based on city/district for demo
|
||||
// In production, these would come from the API
|
||||
const cityCoords: Record<string, [number, number]> = {
|
||||
'Hồ Chí Minh': [10.8231, 106.6297],
|
||||
'Hà Nội': [21.0285, 105.8542],
|
||||
'Đà Nẵng': [16.0544, 108.2022],
|
||||
'Nha Trang': [12.2388, 109.1967],
|
||||
'Cần Thơ': [10.0452, 105.7469],
|
||||
};
|
||||
const base = cityCoords[listing.property.city] || [10.8231, 106.6297];
|
||||
// Add small random offset per listing for visual spread
|
||||
const seed = listing.id.charCodeAt(0) + index;
|
||||
const lat = base[0] + ((seed % 100) - 50) * 0.001;
|
||||
const lng = base[1] + ((seed % 73) - 36) * 0.001;
|
||||
return { listing, lat, lng };
|
||||
});
|
||||
}, [listings]);
|
||||
const DEFAULT_CENTER: [number, number] = [106.6297, 10.8231]; // HCMC [lng, lat]
|
||||
const DEFAULT_ZOOM = 12;
|
||||
|
||||
const handleMarkerClick = (marker: MapMarker) => {
|
||||
setSelectedMarker(marker);
|
||||
onMarkerClick?.(marker.listing);
|
||||
function getMarkerCoords(listing: ListingDetail, index: number): { lat: number; lng: number } {
|
||||
const base = CITY_COORDS[listing.property.city] || [10.8231, 106.6297];
|
||||
const seed = listing.id.charCodeAt(0) + index;
|
||||
return {
|
||||
lat: base[0] + ((seed % 100) - 50) * 0.001,
|
||||
lng: base[1] + ((seed % 73) - 36) * 0.001,
|
||||
};
|
||||
}
|
||||
|
||||
// CSS-based map visualization (no Mapbox dependency required)
|
||||
// Uses a relative coordinate system to position markers
|
||||
const bounds = React.useMemo(() => {
|
||||
if (markers.length === 0) return { minLat: 10, maxLat: 22, minLng: 102, maxLng: 110 };
|
||||
const lats = markers.map((m) => m.lat);
|
||||
const lngs = markers.map((m) => m.lng);
|
||||
const padding = 0.01;
|
||||
return {
|
||||
minLat: Math.min(...lats) - padding,
|
||||
maxLat: Math.max(...lats) + padding,
|
||||
minLng: Math.min(...lngs) - padding,
|
||||
maxLng: Math.max(...lngs) + padding,
|
||||
export function ListingMap({ listings, onMarkerClick, selectedListingId, className }: ListingMapProps) {
|
||||
const mapContainerRef = React.useRef<HTMLDivElement>(null);
|
||||
const mapRef = React.useRef<mapboxgl.Map | null>(null);
|
||||
const markersRef = React.useRef<mapboxgl.Marker[]>([]);
|
||||
const popupRef = React.useRef<mapboxgl.Popup | null>(null);
|
||||
|
||||
const markers: MapMarker[] = React.useMemo(
|
||||
() => listings.map((listing, index) => ({ listing, ...getMarkerCoords(listing, index) })),
|
||||
[listings],
|
||||
);
|
||||
|
||||
// Initialize map
|
||||
React.useEffect(() => {
|
||||
if (!mapContainerRef.current) return;
|
||||
|
||||
const token = process.env['NEXT_PUBLIC_MAPBOX_TOKEN'];
|
||||
if (!token) {
|
||||
console.warn('NEXT_PUBLIC_MAPBOX_TOKEN is not set. Map will not render.');
|
||||
return;
|
||||
}
|
||||
|
||||
mapboxgl.accessToken = token;
|
||||
|
||||
const map = new mapboxgl.Map({
|
||||
container: mapContainerRef.current,
|
||||
style: 'mapbox://styles/mapbox/streets-v12',
|
||||
center: DEFAULT_CENTER,
|
||||
zoom: DEFAULT_ZOOM,
|
||||
attributionControl: false,
|
||||
});
|
||||
|
||||
map.addControl(new mapboxgl.NavigationControl(), 'top-right');
|
||||
map.addControl(new mapboxgl.AttributionControl({ compact: true }), 'bottom-right');
|
||||
|
||||
mapRef.current = map;
|
||||
|
||||
return () => {
|
||||
map.remove();
|
||||
mapRef.current = null;
|
||||
};
|
||||
}, [markers]);
|
||||
}, []);
|
||||
|
||||
// Update markers when listings change
|
||||
React.useEffect(() => {
|
||||
const map = mapRef.current;
|
||||
if (!map) return;
|
||||
|
||||
// Clear existing markers
|
||||
markersRef.current.forEach((m) => m.remove());
|
||||
markersRef.current = [];
|
||||
|
||||
if (markers.length === 0) return;
|
||||
|
||||
const bounds = new mapboxgl.LngLatBounds();
|
||||
|
||||
markers.forEach((marker) => {
|
||||
const el = document.createElement('button');
|
||||
el.className = 'mapbox-price-marker';
|
||||
const isSelected = selectedListingId === marker.listing.id;
|
||||
el.innerHTML = `<span class="${isSelected ? 'selected' : ''}">${formatPrice(marker.listing.priceVND)}</span>`;
|
||||
el.style.cssText = 'border:none;cursor:pointer;background:none;padding:0;';
|
||||
|
||||
el.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
onMarkerClick?.(marker.listing);
|
||||
showPopup(map, marker);
|
||||
});
|
||||
|
||||
const mbMarker = new mapboxgl.Marker({ element: el, anchor: 'bottom' })
|
||||
.setLngLat([marker.lng, marker.lat])
|
||||
.addTo(map);
|
||||
|
||||
markersRef.current.push(mbMarker);
|
||||
bounds.extend([marker.lng, marker.lat]);
|
||||
});
|
||||
|
||||
// Fit bounds with padding
|
||||
if (markers.length > 1) {
|
||||
map.fitBounds(bounds, { padding: 60, maxZoom: 15 });
|
||||
} else {
|
||||
map.flyTo({ center: [markers[0]!.lng, markers[0]!.lat], zoom: 14 });
|
||||
}
|
||||
}, [markers, selectedListingId, onMarkerClick]);
|
||||
|
||||
function showPopup(map: mapboxgl.Map, marker: MapMarker) {
|
||||
popupRef.current?.remove();
|
||||
|
||||
const { listing } = marker;
|
||||
const imgHtml = listing.property.media.length > 0
|
||||
? `<img src="${listing.property.media[0]!.url}" alt="${listing.property.title}" style="width:100%;height:96px;object-fit:cover;border-radius:6px;margin-bottom:8px;" />`
|
||||
: '';
|
||||
|
||||
const popup = new mapboxgl.Popup({ offset: 25, maxWidth: '260px', closeButton: true })
|
||||
.setLngLat([marker.lng, marker.lat])
|
||||
.setHTML(`
|
||||
<div style="font-family:system-ui,sans-serif;">
|
||||
${imgHtml}
|
||||
<p style="font-weight:700;color:hsl(142.1,76.2%,36.3%);font-size:14px;margin:0 0 4px;">
|
||||
${formatPrice(listing.priceVND)} VND
|
||||
</p>
|
||||
<p style="font-size:13px;font-weight:500;margin:0 0 2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
|
||||
${listing.property.title}
|
||||
</p>
|
||||
<p style="font-size:12px;color:#666;margin:0 0 8px;">
|
||||
${listing.property.district}, ${listing.property.city}
|
||||
</p>
|
||||
<div style="display:flex;gap:4px;font-size:11px;margin-bottom:8px;">
|
||||
<span style="background:#f1f5f9;padding:2px 6px;border-radius:4px;">${listing.property.areaM2} m\u00B2</span>
|
||||
${listing.property.bedrooms != null ? `<span style="background:#f1f5f9;padding:2px 6px;border-radius:4px;">${listing.property.bedrooms} PN</span>` : ''}
|
||||
${listing.property.bathrooms != null ? `<span style="background:#f1f5f9;padding:2px 6px;border-radius:4px;">${listing.property.bathrooms} WC</span>` : ''}
|
||||
</div>
|
||||
<a href="/listings/${listing.id}" style="display:block;text-align:center;font-size:12px;font-weight:500;color:hsl(142.1,76.2%,36.3%);text-decoration:none;">
|
||||
Xem chi tiet →
|
||||
</a>
|
||||
</div>
|
||||
`)
|
||||
.addTo(map);
|
||||
|
||||
popupRef.current = popup;
|
||||
}
|
||||
|
||||
const hasToken = typeof process !== 'undefined' && process.env['NEXT_PUBLIC_MAPBOX_TOKEN'];
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={mapRef}
|
||||
className={`relative overflow-hidden rounded-lg border bg-gradient-to-b from-blue-50 to-green-50 ${className || 'h-[500px]'}`}
|
||||
>
|
||||
{/* Grid lines for visual reference */}
|
||||
<div className="absolute inset-0 opacity-10">
|
||||
<div className="h-full w-full"
|
||||
style={{
|
||||
backgroundImage: 'linear-gradient(rgba(0,0,0,0.1) 1px, transparent 1px), linear-gradient(90deg, rgba(0,0,0,0.1) 1px, transparent 1px)',
|
||||
backgroundSize: '50px 50px',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className={`relative overflow-hidden rounded-lg border ${className || 'h-[500px]'}`}>
|
||||
<div ref={mapContainerRef} className="h-full w-full" />
|
||||
|
||||
{/* Markers */}
|
||||
{markers.map((marker) => {
|
||||
const x = ((marker.lng - bounds.minLng) / (bounds.maxLng - bounds.minLng)) * 100;
|
||||
const y = ((bounds.maxLat - marker.lat) / (bounds.maxLat - bounds.minLat)) * 100;
|
||||
const isSelected = selectedMarker?.listing.id === marker.listing.id;
|
||||
|
||||
return (
|
||||
<button
|
||||
key={marker.listing.id}
|
||||
className={`absolute z-10 -translate-x-1/2 -translate-y-full cursor-pointer transition-all hover:z-20 hover:scale-110 ${
|
||||
isSelected ? 'z-20 scale-110' : ''
|
||||
}`}
|
||||
style={{ left: `${Math.min(Math.max(x, 5), 95)}%`, top: `${Math.min(Math.max(y, 5), 90)}%` }}
|
||||
onClick={() => handleMarkerClick(marker)}
|
||||
>
|
||||
<div
|
||||
className={`rounded-full px-2 py-1 text-xs font-bold shadow-md ${
|
||||
isSelected
|
||||
? 'bg-primary text-primary-foreground ring-2 ring-primary/30'
|
||||
: 'bg-white text-foreground hover:bg-primary hover:text-primary-foreground'
|
||||
}`}
|
||||
>
|
||||
{formatPrice(marker.listing.priceVND)}
|
||||
</div>
|
||||
<div className="mx-auto h-2 w-0 border-l-4 border-r-4 border-t-4 border-l-transparent border-r-transparent border-t-current" />
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Selected marker popup */}
|
||||
{selectedMarker && (
|
||||
<div
|
||||
className="absolute z-30 w-64 -translate-x-1/2 rounded-lg border bg-white p-3 shadow-lg"
|
||||
style={{
|
||||
left: `${Math.min(Math.max(((selectedMarker.lng - bounds.minLng) / (bounds.maxLng - bounds.minLng)) * 100, 15), 85)}%`,
|
||||
top: `${Math.min(Math.max(((bounds.maxLat - selectedMarker.lat) / (bounds.maxLat - bounds.minLat)) * 100 - 15, 2), 60)}%`,
|
||||
}}
|
||||
>
|
||||
<button
|
||||
className="absolute right-1 top-1 rounded p-1 text-muted-foreground hover:bg-muted"
|
||||
onClick={(e) => { e.stopPropagation(); setSelectedMarker(null); }}
|
||||
>
|
||||
<svg className="h-3 w-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
{/* Fallback when no Mapbox token */}
|
||||
{!hasToken && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-gradient-to-b from-blue-50 to-green-50">
|
||||
<div className="text-center">
|
||||
<svg className="mx-auto mb-2 h-10 w-10 text-muted-foreground" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 20l-5.447-2.724A1 1 0 013 16.382V5.618a1 1 0 011.447-.894L9 7m0 13l6-3m-6 3V7m6 10l4.553 2.276A1 1 0 0021 18.382V7.618a1 1 0 00-.553-.894L15 4m0 13V4m0 0L9 7" />
|
||||
</svg>
|
||||
</button>
|
||||
{selectedMarker.listing.property.media.length > 0 && (
|
||||
<img
|
||||
src={selectedMarker.listing.property.media[0]?.url}
|
||||
alt={selectedMarker.listing.property.title}
|
||||
className="mb-2 h-24 w-full rounded object-cover"
|
||||
/>
|
||||
)}
|
||||
<p className="text-sm font-bold text-primary">
|
||||
{formatPrice(selectedMarker.listing.priceVND)} VNĐ
|
||||
</p>
|
||||
<p className="line-clamp-1 text-sm font-medium">{selectedMarker.listing.property.title}</p>
|
||||
<p className="line-clamp-1 text-xs text-muted-foreground">
|
||||
{selectedMarker.listing.property.district}, {selectedMarker.listing.property.city}
|
||||
</p>
|
||||
<div className="mt-2 flex gap-1">
|
||||
<Badge variant="secondary" className="text-xs">{selectedMarker.listing.property.areaM2} m²</Badge>
|
||||
{selectedMarker.listing.property.bedrooms != null && (
|
||||
<Badge variant="secondary" className="text-xs">{selectedMarker.listing.property.bedrooms} PN</Badge>
|
||||
)}
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Thiết lập NEXT_PUBLIC_MAPBOX_TOKEN để hiển thị bản đồ
|
||||
</p>
|
||||
</div>
|
||||
<a
|
||||
href={`/listings/${selectedMarker.listing.id}`}
|
||||
className="mt-2 block text-center text-xs font-medium text-primary hover:underline"
|
||||
>
|
||||
Xem chi tiết
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Map controls */}
|
||||
<div className="absolute bottom-3 left-3 flex flex-col gap-1">
|
||||
<div className="rounded bg-white/90 px-2 py-1 text-xs text-muted-foreground shadow">
|
||||
{markers.length} bất động sản trên bản đồ
|
||||
</div>
|
||||
{/* Listing count overlay */}
|
||||
<div className="absolute bottom-3 left-3 rounded bg-white/90 px-2 py-1 text-xs text-muted-foreground shadow">
|
||||
{markers.length} bất động sản trên bản đồ
|
||||
</div>
|
||||
|
||||
{/* Empty state */}
|
||||
{markers.length === 0 && (
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
{markers.length === 0 && hasToken && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-white/60">
|
||||
<p className="text-muted-foreground">Không có bất động sản để hiển thị trên bản đồ</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<style jsx global>{`
|
||||
.mapbox-price-marker span {
|
||||
display: block;
|
||||
background: white;
|
||||
border-radius: 9999px;
|
||||
padding: 4px 8px;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
box-shadow: 0 1px 4px rgba(0,0,0,0.15);
|
||||
white-space: nowrap;
|
||||
transition: all 0.15s;
|
||||
}
|
||||
.mapbox-price-marker:hover span,
|
||||
.mapbox-price-marker span.selected {
|
||||
background: hsl(142.1, 76.2%, 36.3%);
|
||||
color: white;
|
||||
transform: scale(1.1);
|
||||
}
|
||||
.mapboxgl-popup-content {
|
||||
border-radius: 8px !important;
|
||||
padding: 12px !important;
|
||||
box-shadow: 0 4px 12px rgba(0,0,0,0.15) !important;
|
||||
}
|
||||
`}</style>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"lucide-react": "^1.7.0",
|
||||
"mapbox-gl": "^3.21.0",
|
||||
"next": "^14.2.0",
|
||||
"react": "^18.3.0",
|
||||
"react-dom": "^18.3.0",
|
||||
@@ -23,6 +24,7 @@
|
||||
"zustand": "^5.0.12"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/mapbox-gl": "^3.5.0",
|
||||
"@types/node": "^22.0.0",
|
||||
"@types/react": "^18.3.0",
|
||||
"@types/react-dom": "^18.3.0",
|
||||
|
||||
Reference in New Issue
Block a user