Skip to content

Commit

Permalink
fix: change plain js maplibre to use react-map-gl
Browse files Browse the repository at this point in the history
  • Loading branch information
Pinx0 committed Nov 6, 2024
1 parent e2fb432 commit 8a69c3a
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 78 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,22 @@ import { supabase } from '@/lib/supabase/client';
import SolicitudCard from '@/components/SolicitudCard';
import { useRouter, useSearchParams } from 'next/navigation';
import { tiposAyudaOptions } from '@/helpers/constants';
import Map from '@/components/map/map';
import ReactDOMServer from 'react-dom/server';
import Map, { PinMapa } from '@/components/map/map';
// @ts-ignore
import PickupPoint from '@/components/PickupPoint';
import { useTowns } from '@/context/TownProvider';

const PAIPORTA_LAT_LNG = [-0.41667, 39.42333];
const DEFAULT_ZOOM = 12;

export default function Mapa() {
const towns = useTowns();
const searchParams = useSearchParams();
const router = useRouter();

const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [error, setError] = useState<string | null>(null);

const [data, setData] = useState([]);
const [data, setData] = useState<PinMapa[]>([]);

const updateFilter = (filter, value) => {
const updateFilter = (filter: any, value: any) => {
const params = new URLSearchParams(searchParams.toString());
params.set(filter, value);
router.push(`?${params.toString()}`);
Expand All @@ -36,7 +33,7 @@ export default function Mapa() {
acepta: searchParams.get('acepta') || 'todos',
});

const changeDataFilter = (type, newFilter) => {
const changeDataFilter = (type: any, newFilter: any) => {
setFiltroData((prev) => ({
...prev,
[type]: newFilter,
Expand All @@ -45,23 +42,23 @@ export default function Mapa() {
};

useEffect(() => {
function transformHelpRequestToMarker(request) {
function transformHelpRequestToMarker(request: any): PinMapa {
return {
urgency: request.urgency,
coordinates: [request.longitude ?? 0, request.latitude ?? 0],
width: '600px',
descriptionHTML: ReactDOMServer.renderToString(
<SolicitudCard isHref={true} isEdit={false} towns={towns} caso={request} />,
),
latitude: request.latitude ?? 0,
longitude: request.longitude ?? 0,
id: request.id,
popup: <SolicitudCard isHref={true} isEdit={false} towns={towns} caso={request} />,
};
}

function transformPickupRequestToMarker(point) {
function transformPickupRequestToMarker(point: any): PinMapa {
return {
urgency: point.urgency || 'baja',
coordinates: [point.longitude ?? 0, point.latitude ?? 0],
width: '600px',
descriptionHTML: ReactDOMServer.renderToString(<PickupPoint point={point} />),
latitude: point.latitude ?? 0,
longitude: point.longitude ?? 0,
id: point.id,
popup: <PickupPoint point={point} />,
};
}

Expand Down Expand Up @@ -162,7 +159,7 @@ export default function Mapa() {
</div>

<div className="grid gap-4">
<Map markers={data} center={PAIPORTA_LAT_LNG} zoom={DEFAULT_ZOOM} />
<Map markers={data} />
</div>
</>
);
Expand Down
116 changes: 58 additions & 58 deletions src/components/map/map.tsx
Original file line number Diff line number Diff line change
@@ -1,74 +1,74 @@
import { FC, useEffect, useRef } from 'react';
import maplibregl from 'maplibre-gl';
'use client';

import { FC, ReactNode, useRef, useState } from 'react';
import ReactMap, { Popup } from 'react-map-gl/maplibre';
import 'maplibre-gl/dist/maplibre-gl.css';
import { Marker } from 'react-map-gl/maplibre';
import { MapPin } from 'lucide-react';

const urgencyToColor = {
alta: '#ef4444', //text-red-500
media: '#f59e0b', //text-amber-500
baja: '#10b981', //text-emerald-500
};

type MapProps = {
center?: [number, number];
zoom?: number;
markers?: {
coordinates: [number, number];
urgency: 'alta' | 'media' | 'baja';
descriptionHTML: string;
width: number;
}[];
export type PinMapa = {
id: string;
latitude: number;
longitude: number;
urgency: 'alta' | 'media' | 'baja';
popup: ReactNode;
};

const Map: FC<MapProps> = ({ center = [0, 0], zoom = 2, markers = [] }) => {
const mapContainerRef = useRef<HTMLDivElement | null>(null);
const mapRef = useRef<maplibregl.Map | null>(null);
const markerRefs = useRef<maplibregl.Marker[]>([]);

useEffect(() => {
if (!mapRef.current) {
mapRef.current = new maplibregl.Map({
container: mapContainerRef.current!,
style: 'https://basemaps.cartocdn.com/gl/positron-gl-style/style.json',
center: center,
zoom: zoom,
});
mapRef.current.addControl(new maplibregl.NavigationControl(), 'top-right');
} else {
// Update center and zoom when props change
mapRef.current.setCenter(center);
mapRef.current.setZoom(zoom);
}

// Clear existing markers
markerRefs.current.forEach((marker) => marker.remove());
markerRefs.current = [];

// Add new markers
markers.forEach((markerData) => {
const marker = new maplibregl.Marker({
color: urgencyToColor[markerData.urgency],
})
.setLngLat(markerData.coordinates)
.setPopup(
new maplibregl.Popup({
className: 'map-popup',
maxWidth: `${markerData.width}px`,
anchor: 'left',
}).setHTML(markerData.descriptionHTML),
)
.addTo(mapRef.current!);
type MapProps = {
markers?: PinMapa[];
};

markerRefs.current.push(marker);
});
const PAIPORTA_LAT = 39.42333;
const PAIPORTA_LNG = -0.41667;
const DEFAULT_ZOOM = 12;

// Clean up function to remove markers only
return () => {
markerRefs.current.forEach((marker) => marker.remove());
markerRefs.current = [];
};
}, [center, zoom, markers]);
const Map: FC<MapProps> = ({ markers = [] }) => {
const [selectedMarker, setSelectedMarker] = useState<PinMapa | null>(null);

return <div ref={mapContainerRef} style={{ width: '100%', height: '75vh' }} />;
console.log(selectedMarker);
return (
<ReactMap
initialViewState={{
longitude: PAIPORTA_LNG,
latitude: PAIPORTA_LAT,
zoom: DEFAULT_ZOOM,
}}
style={{ width: '100%', height: '75vh' }}
mapStyle="https://basemaps.cartocdn.com/gl/positron-gl-style/style.json"
>
{markers.map((m) => {
return (
<Marker
key={m.id}
color={urgencyToColor[m.urgency]}
longitude={-0.4}
latitude={39.42333}
onClick={() => setSelectedMarker(m)}
anchor="bottom"
>
<MapPin className="h-6 w-6 text-orange-500" />
</Marker>
);
})}
{selectedMarker && (
<Popup
longitude={-0.4}
latitude={39.42333}
className={'map-popup'}
anchor="top"
onClose={() => setSelectedMarker(null)}
>
{selectedMarker.popup}
</Popup>
)}
</ReactMap>
);
};

export default Map;

0 comments on commit 8a69c3a

Please sign in to comment.