added Collision handling for open popups

This commit is contained in:
PxlLoewe
2025-04-11 21:54:06 -07:00
parent 280c1abfde
commit 9ddbbce139
4 changed files with 303 additions and 183 deletions

View File

@@ -2,8 +2,9 @@ import { Aircraft, useAircraftsStore } from "_store/aircraftsStore";
import { Marker, Popup, useMap } from "react-leaflet"; import { Marker, Popup, useMap } from "react-leaflet";
import { DivIcon, Marker as LMarker, Popup as LPopup } from "leaflet"; import { DivIcon, Marker as LMarker, Popup as LPopup } from "leaflet";
import { useMapStore } from "_store/mapStore"; import { useMapStore } from "_store/mapStore";
import { Fragment, useEffect, useRef, useState } from "react"; import { Fragment, useCallback, useEffect, useRef, useState } from "react";
import { cn } from "helpers/cn"; import { cn } from "helpers/cn";
import { House, Route } from "lucide-react";
export const FMS_STATUS_COLORS: { [key: string]: string } = { export const FMS_STATUS_COLORS: { [key: string]: string } = {
"0": "rgb(126,0,5)", "0": "rgb(126,0,5)",
@@ -31,191 +32,293 @@ export const FMS_STATUS_TEXT_COLORS: { [key: string]: string } = {
"9": "rgb(42,217,42)", "9": "rgb(42,217,42)",
}; };
export const AircraftMarker = (props: any) => { const AircraftLabel = ({ aircraft }: { aircraft: Aircraft }) => {
const { openAircraftMarker, setOpenAircraftMarker } = useMapStore(
(state) => state,
);
const aircrafts = useAircraftsStore((state) => state.aircrafts); const aircrafts = useAircraftsStore((state) => state.aircrafts);
const map = useMap(); const map = useMap();
const markerRef = useRef<LMarker>(null);
const popupRef = useRef<LPopup>(null);
const { openAircraftMarker, setOpenAircraftMarker } = useMapStore(
(store) => store,
);
useEffect(() => {
const handleClick = () => {
const open = openAircraftMarker.includes(aircraft.id);
if (open) {
setOpenAircraftMarker({
open: [],
close: [aircraft.id],
});
} else {
setOpenAircraftMarker({
open: [aircraft.id],
close: [],
});
}
};
markerRef.current?.on("click", handleClick);
return () => {
markerRef.current?.off("click", handleClick);
};
}, [markerRef.current, aircraft.id, openAircraftMarker]);
const [anchor, setAnchor] = useState<
"topleft" | "topright" | "bottomleft" | "bottomright"
>("topleft");
const handleLabelConflict = useCallback(() => {
const otherMarkers = document.querySelectorAll(".aircraft-collision");
// get markers and check if they are overlapping
const ownMarker = openAircraftMarker.includes(aircraft.id)
? document.querySelector(`#aircraft-popup-${aircraft.id}`)
: document.querySelector(`#aircraft-marker-${aircraft.id}`);
if (!otherMarkers || !ownMarker) return;
const marksersInCluster = Array.from(otherMarkers).filter((marker) => {
if (
openAircraftMarker.includes(aircraft.id) &&
marker.id === `aircraft-marker-${aircraft.id}`
)
return false;
const rect1 = (marker as HTMLElement).getBoundingClientRect();
const rect2 = (ownMarker as HTMLElement).getBoundingClientRect();
return !(
rect1.right < rect2.left ||
rect1.left > rect2.right ||
rect1.bottom < rect2.top ||
rect1.top > rect2.bottom
);
});
// get the center of all overlapping markers
const markersPosition = marksersInCluster.map((marker) => {
const rect = (marker as HTMLElement).getBoundingClientRect();
return {
x: rect.left + rect.width / 2,
y: rect.top + rect.height / 2,
};
});
const ownMarkerBounds = (ownMarker as HTMLElement).getBoundingClientRect();
const ownMarkerPosition = {
x: ownMarkerBounds.left + ownMarkerBounds.width / 2,
y: ownMarkerBounds.top + ownMarkerBounds.height / 2,
};
const centerOfOverlappingMarkers = markersPosition.reduce(
(acc, pos) => {
if (acc.x === 0 && acc.y === 0) return pos;
return {
x: (acc.x + pos.x) / 2,
y: (acc.y + pos.y) / 2,
};
},
{
x: 0,
y: 0,
},
);
if (marksersInCluster.length > 1) {
if (centerOfOverlappingMarkers.y < ownMarkerPosition.y) {
if (centerOfOverlappingMarkers.x > ownMarkerPosition.x) {
setAnchor("topright");
} else {
setAnchor("topleft");
}
} else {
if (centerOfOverlappingMarkers.x > ownMarkerPosition.x) {
setAnchor("bottomright");
} else {
setAnchor("bottomleft");
}
}
} else {
// Default
setAnchor("topleft");
}
}, [openAircraftMarker, aircraft.id]);
useEffect(() => {
handleLabelConflict();
}, [aircrafts, openAircraftMarker]);
useEffect(() => {});
useEffect(() => {
handleLabelConflict();
map.on("zoom", handleLabelConflict);
return () => {
map.off("zoom", handleLabelConflict);
};
}, [map, openAircraftMarker]);
const getMarkerHTML = ( const getMarkerHTML = (
aircraft: Aircraft, aircraft: Aircraft,
anchor: "topleft" | "topright" | "bottomleft" | "bottomright", anchor: "topleft" | "topright" | "bottomleft" | "bottomright",
) => { ) => {
return `<div return `<div
class="${cn(
" relative w-[140px] transform flex items-center gap-2 px-2 z-100",
anchor.includes("right") && "-translate-x-full",
anchor.includes("bottom") && "-translate-y-full",
)}"
style="
background-color: ${FMS_STATUS_COLORS[aircraft.fmsStatus]};
${openAircraftMarker.includes(aircraft.id) ? "opacity: 0;" : ""}
">
<div
class="${cn( class="${cn(
"absolute w-4 h-4 z-99", "relative w-[140px] transform flex items-center gap-2 px-2 z-100",
anchor.includes("left") ? "-left-[2px]" : "-right-[2px]", anchor.includes("right") && "-translate-x-full",
anchor.includes("top") ? "-top-[2px]" : "-bottom-[2px]", anchor.includes("bottom") && "-translate-y-full",
)}" )}"
style=" style="
${anchor.includes("left") ? `border-left: 3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]};` : `border-right: 3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]};`} background-color: ${FMS_STATUS_COLORS[aircraft.fmsStatus]};
${anchor.includes("top") ? `border-top: 3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]};` : `border-bottom: 3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]};`} ${openAircraftMarker.includes(aircraft.id) ? "opacity: 0; pointer-events: none;" : ""}
" ">
></div>
<span <div
class="font-semibold text-xl" class="${cn(
style="color: ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]};" "absolute w-4 h-4 z-99",
> anchor.includes("left") ? "-left-[2px]" : "-right-[2px]",
${aircraft.fmsStatus} anchor.includes("top") ? "-top-[2px]" : "-bottom-[2px]",
</span> )}"
<span class="text-white text-[15px]"> style="
${aircraft.bosName} ${anchor.includes("left") ? `border-left: 3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]};` : `border-right: 3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]};`}
</span> ${anchor.includes("top") ? `border-top: 3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]};` : `border-bottom: 3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]};`}
<div "
data-aircraft-id="${aircraft.id}" ></div>
id="aircraft-marker-${aircraft.id}" <span
class="${cn( class="font-semibold text-xl"
"aircraft-marker absolute w-[200%] h-[200%] top-0 left-0 transform", style="color: ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]};"
anchor.includes("left") && "-translate-x-1/2", >
anchor.includes("top") && "-translate-y-1/2", ${aircraft.fmsStatus}
)}" </span>
></div> <span class="text-white text-[15px]">
</div>`; ${aircraft.bosName}
</span>
<div
data-aircraft-id="${aircraft.id}"
id="aircraft-marker-${aircraft.id}"
class="${cn(
"aircraft-collision absolute w-[200%] h-[200%] top-0 left-0 transform pointer-events-none",
anchor.includes("left") && "-translate-x-1/2",
anchor.includes("top") && "-translate-y-1/2",
)}"
></div>
</div>`;
}; };
return aircrafts.map((aircraft) => { return (
const markerRef = useRef<LMarker>(null); <Fragment key={aircraft.id}>
const popupRef = useRef<LPopup>(null); <Marker
ref={markerRef}
useEffect(() => { position={[aircraft.location.lat, aircraft.location.lon]}
const handleClick = () => { icon={
const open = openAircraftMarker.includes(aircraft.id); new DivIcon({
if (open) { iconAnchor: [0, 0],
setOpenAircraftMarker({ html: getMarkerHTML(aircraft, anchor),
open: [], })
close: [aircraft.id],
});
} else {
setOpenAircraftMarker({
open: [aircraft.id],
close: [],
});
} }
}; />
markerRef.current?.on("click", handleClick); {openAircraftMarker.includes(aircraft.id) && (
return () => { <Popup
markerRef.current?.off("click", handleClick); ref={popupRef}
};
}, [markerRef.current, aircraft.id, openAircraftMarker]);
// TODO: Get Overlapping Markers and make them opientate away from the center
const [anchor, setAnchor] = useState<
"topleft" | "topright" | "bottomleft" | "bottomright"
>("topleft");
useEffect(() => {
const handleZoom = () => {
const otherMarkers = document.querySelectorAll(".aircraft-marker");
// get markers and check if they are overlapping
const ownMarker = document.querySelector(
`#aircraft-marker-${aircraft.id}`,
);
if (!otherMarkers || !ownMarker) return;
const marksersInCluster = Array.from(otherMarkers).filter((marker) => {
// if (marker.id === `aircraft-marker-${aircraft.id}`) return false;
const rect1 = (marker as HTMLElement).getBoundingClientRect();
const rect2 = (ownMarker as HTMLElement).getBoundingClientRect();
return !(
rect1.right < rect2.left ||
rect1.left > rect2.right ||
rect1.bottom < rect2.top ||
rect1.top > rect2.bottom
);
});
// get the center of all overlapping markers
const markersPosition = marksersInCluster.map((marker) => {
const rect = (marker as HTMLElement).getBoundingClientRect();
return {
x: rect.left + rect.width / 2,
y: rect.top + rect.height / 2,
};
});
const ownMarkerBounds = (
ownMarker as HTMLElement
).getBoundingClientRect();
const ownMarkerPosition = {
x: ownMarkerBounds.left + ownMarkerBounds.width / 2,
y: ownMarkerBounds.top + ownMarkerBounds.height / 2,
};
const centerOfOverlappingMarkers = markersPosition.reduce(
(acc, pos) => {
if (acc.x === 0 && acc.y === 0) return pos;
return {
x: (acc.x + pos.x) / 2,
y: (acc.y + pos.y) / 2,
};
},
{
x: 0,
y: 0,
},
);
if (marksersInCluster.length > 1) {
if (centerOfOverlappingMarkers.y < ownMarkerPosition.y) {
if (centerOfOverlappingMarkers.x > ownMarkerPosition.x) {
setAnchor("topright");
} else {
setAnchor("topleft");
}
} else {
if (centerOfOverlappingMarkers.x > ownMarkerPosition.x) {
setAnchor("bottomright");
} else {
setAnchor("bottomleft");
}
}
} else {
// Default
setAnchor("topleft");
}
};
map.on("zoom", handleZoom);
return () => {
map.off("zoom", handleZoom);
};
}, [map]);
return (
<Fragment key={aircraft.id}>
<Marker
ref={markerRef}
position={[aircraft.location.lat, aircraft.location.lon]} position={[aircraft.location.lat, aircraft.location.lon]}
icon={ autoClose={false}
new DivIcon({ closeOnClick={false}
iconAnchor: [0, 0], autoPan={false}
html: getMarkerHTML(aircraft, anchor), className={cn("relative")}
}) >
} <div
/> className={cn(
{openAircraftMarker.includes(aircraft.id) && ( "w-[200px] h-[150px] pointer-events-auto bg-base-100 relative",
<Popup anchor.includes("right") && "-translate-x-full",
ref={popupRef} anchor.includes("bottom") && "-translate-y-full",
position={[aircraft.location.lat, aircraft.location.lon]} )}
autoClose={false}
closeOnClick={false}
autoPan={false}
className="outline-red"
> >
<div className="p-2 bg-white">Alla</div> <div
</Popup> data-aircraft-id={aircraft.id}
)} id={`aircraft-popup-${aircraft.id}`}
</Fragment> className={cn(
); "aircraft-collision absolute w-[200%] h-[200%] top-0 left-0 transform pointer-events-none",
}); anchor.includes("left") && "-translate-x-1/2",
anchor.includes("top") && "-translate-y-1/2",
)}
></div>
<div
className={cn(
"absolute w-[calc(100%+2px)] h-4 z-99",
anchor.includes("left") ? "-left-[2px]" : "-right-[2px]",
anchor.includes("top") ? "-top-[2px]" : "-bottom-[2px]",
)}
style={{
borderLeft: anchor.includes("left")
? `3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]}`
: "",
borderRight: anchor.includes("right")
? `3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]}`
: "",
borderTop: anchor.includes("top")
? `3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]}`
: "",
borderBottom: anchor.includes("bottom")
? `3px solid ${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]}`
: "",
}}
/>
<div>
<div
className="flex gap-[2px] text-white pb-0.5"
style={{
backgroundColor: `${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]}`,
}}
>
<div
className="p-2 flex justify-center items-center"
style={{
backgroundColor: `${FMS_STATUS_COLORS[aircraft.fmsStatus]}`,
}}
>
<House className="text-sm " />
</div>
<div
className="p-2 flex justify-center items-center"
style={{
backgroundColor: `${FMS_STATUS_COLORS[aircraft.fmsStatus]}`,
}}
>
<Route className="text-sm " />
</div>
<div
className="flex justify-center items-center text-2xl p-2"
style={{
backgroundColor: `${FMS_STATUS_COLORS[aircraft.fmsStatus]}`,
color: `${FMS_STATUS_TEXT_COLORS[aircraft.fmsStatus]}`,
}}
>
{aircraft.fmsStatus}
</div>
<div
className="p-2 flex-1 flex justify-center items-center"
style={{
backgroundColor: `${FMS_STATUS_COLORS[aircraft.fmsStatus]}`,
}}
>
<span className="text-sm text-white">Einsatz 250411</span>
</div>
</div>
</div>
</div>
</Popup>
)}
</Fragment>
);
};
export const AircraftMarker = (props: any) => {
const { openAircraftMarker, setOpenAircraftMarker } = useMapStore(
(state) => state,
);
const aircrafts = useAircraftsStore((state) => state.aircrafts);
const map = useMap();
return aircrafts.map((aircraft) => (
<AircraftLabel key={aircraft.id} aircraft={aircraft} />
));
}; };

View File

@@ -5,14 +5,25 @@ import { Popup, useMap } from "react-leaflet";
export const ContextMenu = () => { export const ContextMenu = () => {
const map = useMap(); const map = useMap();
const { contextMenu, setContextMenu, setSearchElements } = useMapStore(); const { contextMenu, setContextMenu, setSearchElements, setSearchPopup } =
useMapStore();
useEffect(() => { useEffect(() => {
map.on("contextmenu", (e) => { const handleContextMenu = (e: any) => {
// setOpenMissionMarker({ open: [], close: openMissionMarker });
setContextMenu({ lat: e.latlng.lat, lng: e.latlng.lng }); setContextMenu({ lat: e.latlng.lat, lng: e.latlng.lng });
// setSearchPopup(null); };
}); const handleClick = (e: any) => {
setContextMenu(null);
setSearchPopup(null);
};
map.on("contextmenu", handleContextMenu);
map.on("click", handleClick);
return () => {
map.off("contextmenu", handleContextMenu);
map.off("click", handleClick);
};
}, [contextMenu]); }, [contextMenu]);
if (!contextMenu) return null; if (!contextMenu) return null;
@@ -27,7 +38,7 @@ export const ContextMenu = () => {
{/* // TODO: maske: */} {/* // TODO: maske: */}
<div className="absolute transform -translate-y-1/2 z-1000 opacity-100 pointer-events-auto p-3"> <div className="absolute transform -translate-y-1/2 z-1000 opacity-100 pointer-events-auto p-3">
<button <button
className="btn btn-sm rounded-full bg-amber-600 hover:bg-amber-700 aspect-square" className="btn btn-sm rounded-full bg-rescuetrack aspect-square"
onClick={async () => { onClick={async () => {
const address = await fetch( const address = await fetch(
`https://nominatim.openstreetmap.org/reverse?lat=${contextMenu.lat}&lon=${contextMenu.lng}&format=json`, `https://nominatim.openstreetmap.org/reverse?lat=${contextMenu.lat}&lon=${contextMenu.lng}&format=json`,
@@ -62,7 +73,7 @@ export const ContextMenu = () => {
<MapPinned size={20} /> <MapPinned size={20} />
</button> </button>
<button <button
className="btn btn-sm rounded-full bg-amber-600 hover:bg-amber-700 aspect-square" className="btn btn-sm rounded-full bg-rescuetrack aspect-square"
onClick={async () => { onClick={async () => {
const res = await fetch( const res = await fetch(
`https://overpass-api.de/api/interpreter?data=${encodeURIComponent(` `https://overpass-api.de/api/interpreter?data=${encodeURIComponent(`

View File

@@ -11,8 +11,7 @@ export const MissionMarker = ({
}: { }: {
mission: MissionOptionalDefaults; mission: MissionOptionalDefaults;
}) => { }) => {
const { openMissionMarker, setOpenMissionMarker, setSearchPopup } = const { openMissionMarker, setOpenMissionMarker } = useMapStore();
useMapStore();
const [zoom, setZoom] = useState(0); const [zoom, setZoom] = useState(0);
const map = useMap(); const map = useMap();
const markerRef = useRef<LMarker<any>>(null); const markerRef = useRef<LMarker<any>>(null);
@@ -31,12 +30,19 @@ export const MissionMarker = ({
useEffect(() => { useEffect(() => {
const handleClick = () => { const handleClick = () => {
if (mission.id) { if (!mission.id) return;
if (!openMissionMarker.includes(mission.id)) {
setOpenMissionMarker({ setOpenMissionMarker({
open: [mission.id], open: [mission.id],
close: [], close: [],
}); });
// setSearchPopup(null); // setSearchPopup(null);
} else {
setOpenMissionMarker({
open: [],
close: [mission.id],
});
// setSearchPopup(null);
} }
}; };
markerRef.current?.on("click", handleClick); markerRef.current?.on("click", handleClick);

Binary file not shown.