Fix: Zuverlässige Anzeige von poiTypName mit Fremdschlüssel in den Markern sichergestellt

- Implementierung der Fremdschlüssel-Logik für die `poiTyp`-Daten in `MapComponent`.
- Nutzung einer Map, um die Fremdschlüssel-Beziehung zwischen `poiTyp`-IDs und deren Namen effizient zu verwalten.
- Sicherstellung, dass `poiTypName` korrekt in Marker-Popups angezeigt wird, indem die Fremdschlüssel-Beziehung geprüft wird.
- Verbesserte Bedingungsprüfung sorgt dafür, dass die Popups nun die richtigen `poiTypName`-Werte anzeigen, oder als Fallback "Unbekannt" verwendet wird.
- Effekt-Logik wurde so angepasst, dass Marker nur aktualisiert werden, wenn die `poiTyp`-Daten vollständig geladen sind.
This commit is contained in:
ISA
2024-05-06 08:15:31 +02:00
parent cc0e3e726a
commit dca6e3db8d
4 changed files with 95 additions and 74 deletions

View File

@@ -18,13 +18,17 @@ import { selectedAreaState } from "../store/atoms/selectedAreaState.js";
import { zoomTriggerState } from "../store/atoms/zoomTriggerState.js"; import { zoomTriggerState } from "../store/atoms/zoomTriggerState.js";
import { poiTypState } from "../store/atoms/poiTypState.js"; import { poiTypState } from "../store/atoms/poiTypState.js";
import ShowAddStationPopup from "./ShowAddStationPopup"; import ShowAddStationPopup from "./ShowAddStationPopup";
import { poiReadFromDbTriggerAtom } from '../store/atoms/poiReadFromDbTriggerAtom'; import { poiReadFromDbTriggerAtom } from "../store/atoms/poiReadFromDbTriggerAtom";
//import { createRoot } from "react-dom/client"; //import { createRoot } from "react-dom/client";
const MapComponent = ({ locations, onLocationUpdate }) => { const MapComponent = ({ locations, onLocationUpdate }) => {
const [isPoiTypLoaded, setIsPoiTypLoaded] = useState(false);
const [poiTypMap, setPoiTypMap] = useState(new Map());
const [showPopup, setShowPopup] = useState(false); const [showPopup, setShowPopup] = useState(false);
const [popupCoordinates, setPopupCoordinates] = useState({ lat: 52.52, lng: 13.4050 }); // Beispielkoordinaten const [popupCoordinates, setPopupCoordinates] = useState({
lat: 52.52,
lng: 13.405,
}); // Beispielkoordinaten
const openPopup = () => setShowPopup(true); const openPopup = () => setShowPopup(true);
const closePopup = () => setShowPopup(false); const closePopup = () => setShowPopup(false);
@@ -39,7 +43,6 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
setShowPopup(true); setShowPopup(true);
}; };
const poiReadTrigger = useRecoilValue(poiReadFromDbTriggerAtom); const poiReadTrigger = useRecoilValue(poiReadFromDbTriggerAtom);
const [poiTypData, setPoiTypData] = useState(poiTypState); // Recoil State verwenden const [poiTypData, setPoiTypData] = useState(poiTypState); // Recoil State verwenden
const poiLayerRef = useRef(null); // Referenz auf die Layer-Gruppe für Datenbank-Marker const poiLayerRef = useRef(null); // Referenz auf die Layer-Gruppe für Datenbank-Marker
@@ -277,7 +280,7 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
zoomControl: false, zoomControl: false,
contextmenu: true, contextmenu: true,
contextmenuItems: [ contextmenuItems: [
{ text: "Station hinzufügen", callback: addStationCallback }, { text: "Station hinzufügen", callback: addStationCallback },
{ {
text: "Station öffnen (Tab)", text: "Station öffnen (Tab)",
icon: "img/screen_new.png", icon: "img/screen_new.png",
@@ -347,6 +350,7 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
} }
} }
//---------------------------------- //----------------------------------
// poiTyp Daten hinzufügen
//------------------------------------------ //------------------------------------------
// Funktion zum Abrufen der poiTyp Daten // Funktion zum Abrufen der poiTyp Daten
@@ -360,7 +364,10 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
console.error("Fehler beim Abrufen der poiTyp Daten:", error); console.error("Fehler beim Abrufen der poiTyp Daten:", error);
} }
}; };
console.log("trigger in MapComponent.js in fetchPoiTypData:", poiReadTrigger); console.log(
"trigger in MapComponent.js in fetchPoiTypData:",
poiReadTrigger
);
fetchPoiTypData(); fetchPoiTypData();
}, []); }, []);
@@ -429,14 +436,14 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
loadData(); loadData();
}; };
// Kontextmenü Callback für "Station hinzufügen" // Kontextmenü Callback für "Station hinzufügen"
const addStationCallback = (event) => { const addStationCallback = (event) => {
setPopupCoordinates(event.latlng); // Koordinaten des Klicks verwenden setPopupCoordinates(event.latlng); // Koordinaten des Klicks verwenden
setShowPopup(true); // Popup öffnen setShowPopup(true); // Popup öffnen
}; };
//-----Kontextmenu----ende------------ //-----Kontextmenu----ende------------
// Ensure this function is only called when map is initialized and available // Ensure this function is only called when map is initialized and available
/* const showAddStationPopup = (e, map) => { /* const showAddStationPopup = (e, map) => {
const container = L.DomUtil.create("div"); const container = L.DomUtil.create("div");
// Create a root container for the React component inside the popup // Create a root container for the React component inside the popup
@@ -458,7 +465,7 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
}; */ }; */
// Inside your ShowAddStationPopup component // Inside your ShowAddStationPopup component
/* useEffect(() => { /* useEffect(() => {
// Cleanup function to unmount React component // Cleanup function to unmount React component
return () => { return () => {
if (container._reactRoot) { if (container._reactRoot) {
@@ -470,7 +477,7 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
//------------------------------------------ //------------------------------------------
// Hinzufügen eines neuen Standorts (Marker) in MySQL-DB-Tabelle (poi) // Hinzufügen eines neuen Standorts (Marker) in MySQL-DB-Tabelle (poi)
/* async function handleSubmit(event) { /* async function handleSubmit(event) {
event.preventDefault(); event.preventDefault();
const form = event.target; const form = event.target;
@@ -545,7 +552,27 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
return path; return path;
} }
//------------------------------------------
// Funktion, um die name und idPoiTyp von `poiTyp` MySQL DB Tabelle in einer Map zu speichern
useEffect(() => {
const fetchPoiTypData = async () => {
try {
const response = await fetch("/api/readPoiTyp");
const data = await response.json();
const map = new Map();
data.forEach((item) => map.set(item.idPoiTyp, item.name));
setPoiTypMap(map);
setIsPoiTypLoaded(true); // Daten wurden erfolgreich geladen
console.log("poiTypMap:", map);
const poiTypName = poiTypMap.get(0) || "Unbekannt";
console.log("poiTypName:", poiTypName);
} catch (error) {
console.error("Fehler beim Abrufen der poiTyp-Daten:", error);
}
};
fetchPoiTypData();
}, []);
//------------------------------------------ //------------------------------------------
let dbLayer = null; let dbLayer = null;
useEffect(() => { useEffect(() => {
@@ -576,25 +603,27 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
map.removeLayer(poiLayerRef.current); map.removeLayer(poiLayerRef.current);
poiLayerRef.current = new L.LayerGroup().addTo(map); poiLayerRef.current = new L.LayerGroup().addTo(map);
} }
locations.forEach((location) => { locations.forEach((location) => {
// Fügen Sie hier die Logik hinzu, um Marker zu erstellen und zu konfigurieren // Fügen Sie hier die Logik hinzu, um Marker zu erstellen und zu konfigurieren
}); });
}; };
console.log("trigger in MapComponent.js:", poiReadTrigger); console.log("trigger in MapComponent.js:", poiReadTrigger);
}, [map,locations, poiReadTrigger]); // Dieser Effekt läuft nur, wenn sich `map` ändert }, [map, locations, poiReadTrigger]); // Dieser Effekt läuft nur, wenn sich `map` ändert
//------------------------------------------ //------------------------------------------
// poiLayerRef // poiLayerRef(poiDbLayer) POI hinzufügen
//-------------------------------------------- //--------------------------------------------
useEffect(() => { useEffect(() => {
if (map && poiLayerRef.current) { if (map && poiLayerRef.current && isPoiTypLoaded) {
// Entfernen Sie die bestehende Ebene und erstellen Sie eine neue // Entfernen Sie die bestehende Ebene und erstellen Sie eine neue
map.removeLayer(poiLayerRef.current); map.removeLayer(poiLayerRef.current);
poiLayerRef.current = new L.LayerGroup().addTo(map); poiLayerRef.current = new L.LayerGroup().addTo(map);
// Fügen Sie die aktualisierten Marker hinzu // Fügen Sie die aktualisierten Marker hinzu
locations.forEach((location) => { locations.forEach((location) => {
const { latitude, longitude } = parsePoint(location.position); const { latitude, longitude } = parsePoint(location.position);
const poiTypName = poiTypMap.get(location.idPoiTyp) || "Unbekannt ";
const marker = L.marker([latitude, longitude], { const marker = L.marker([latitude, longitude], {
icon: L.icon({ icon: L.icon({
iconUrl: "/img/icons/green-marker-icon.png", iconUrl: "/img/icons/green-marker-icon.png",
@@ -605,14 +634,12 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
draggable: true, draggable: true,
id: location.idPoi, id: location.idPoi,
}); });
// Popup konfigurieren // Popup konfigurieren
marker.bindPopup( marker.bindPopup(
`<b>${location.description || "Unbekannt"}</b><br>Type: ${ `<b>${location.description || "Unbekannt"}</b><br>Type: ${poiTypName}<br>Lat: ${latitude.toFixed(5)}, Lng: ${longitude.toFixed(5)}`
location.idPoiTyp || "N/A"
}<br>Lat: ${latitude.toFixed(5)}, Lng: ${longitude.toFixed(5)}`
); );
// Event-Handler hinzufügen // Event-Handler hinzufügen
marker.on("mouseover", function () { marker.on("mouseover", function () {
this.openPopup(); this.openPopup();
@@ -620,7 +647,7 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
marker.on("mouseout", function () { marker.on("mouseout", function () {
this.closePopup(); this.closePopup();
}); });
marker.on("dragend", (e) => { marker.on("dragend", (e) => {
const newLat = e.target.getLatLng().lat; const newLat = e.target.getLatLng().lat;
const newLng = e.target.getLatLng().lng; const newLng = e.target.getLatLng().lng;
@@ -630,13 +657,12 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
console.log("trigger in MapComponent.js:", poiReadTrigger); console.log("trigger in MapComponent.js:", poiReadTrigger);
}); });
}); });
marker.addTo(poiLayerRef.current); marker.addTo(poiLayerRef.current);
}); });
} }
}, [map, locations, onLocationUpdate, poiReadTrigger, isPoiTypLoaded]);
}, [map, locations, onLocationUpdate,poiReadTrigger]);
//------------------------------------------ //------------------------------------------
function parsePoint(position) { function parsePoint(position) {
@@ -1522,8 +1548,7 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
// Logik zur Aktualisierung der Map hier hinzufügen // Logik zur Aktualisierung der Map hier hinzufügen
// Beispiel: Daten neu laden oder aktualisieren // Beispiel: Daten neu laden oder aktualisieren
}, [poiReadTrigger]);
}, [poiReadTrigger]);
//--------------------------------------------------------- //---------------------------------------------------------
return ( return (
@@ -1572,7 +1597,6 @@ const MapComponent = ({ locations, onLocationUpdate }) => {
)} )}
</div> </div>
<DataSheet className="z-50" /> <DataSheet className="z-50" />
<div <div

View File

@@ -1,22 +1,21 @@
// components/ShowAddStationPopup.js // components/ShowAddStationPopup.js
import React, { useState, useEffect, use } from "react"; import React, { useState, useEffect, use } from "react";
import ReactDOM from "react-dom"; import ReactDOM from "react-dom";
import { useRecoilValue ,useRecoilState, useSetRecoilState } from "recoil"; import { useRecoilValue, useRecoilState, useSetRecoilState } from "recoil";
import { readPoiMarkersStore } from "../store/selectors/readPoiMarkersStore"; import { readPoiMarkersStore } from "../store/selectors/readPoiMarkersStore";
import { poiReadFromDbTriggerAtom } from '../store/atoms/poiReadFromDbTriggerAtom'; import { poiReadFromDbTriggerAtom } from "../store/atoms/poiReadFromDbTriggerAtom";
const ShowAddStationPopup = ({ onClose, map, latlng }) => { const ShowAddStationPopup = ({ onClose, map, latlng }) => {
const [poiTypData, setpoiTypData] = useState(); // Recoil State verwenden
const [poiTypData2, setPoiTypData2] = useState(); // Recoil State verwenden
const [name, setName] = useState(""); const [name, setName] = useState("");
const [poiTypeId, setPoiTypeId] = useState(""); // Initialize as string const [poiTypeId, setPoiTypeId] = useState(""); // Initialize as string
const [poiTypeName, setPoiTypeName] = useState(""); // Initialize as string
const [latitude] = useState(latlng.lat.toFixed(5)); const [latitude] = useState(latlng.lat.toFixed(5));
const [longitude] = useState(latlng.lng.toFixed(5)); const [longitude] = useState(latlng.lng.toFixed(5));
const setLoadData = useSetRecoilState(readPoiMarkersStore); const setLoadData = useSetRecoilState(readPoiMarkersStore);
const setTrigger = useSetRecoilState(poiReadFromDbTriggerAtom); const setTrigger = useSetRecoilState(poiReadFromDbTriggerAtom);
/* useEffect(() => {
/* useEffect(() => {
if (map && loadData) { if (map && loadData) {
console.log("Map and loadData are defined in ShowAddStationPopup.js", map); console.log("Map and loadData are defined in ShowAddStationPopup.js", map);
@@ -27,15 +26,16 @@ const ShowAddStationPopup = ({ onClose, map, latlng }) => {
} }
}, [map, loadData]); */ }, [map, loadData]); */
// In Kontextmenü-Formular Typen anzeigen // In Kontextmenü-Formular Typen anzeigen
useEffect(() => { useEffect(() => {
const fetchPoiTypData2 = async () => { const fetchpoiTypData = async () => {
try { try {
const response = await fetch("/api/readPoiTyp"); const response = await fetch("/api/readPoiTyp");
const data = await response.json(); const data = await response.json();
setPoiTypData2(data); setpoiTypData(data);
if (data && data.length > 0) { if (data && data.length > 0) {
setPoiTypeId(data[0].idPoiTyp); // Set initial poiTypeId to the id of the first poiType setPoiTypeId(data[0].idPoiTyp); // Set initial poiTypeId to the id of the first poiType
setPoiTypeName(data[1].name); // Set initial poiTypeName to the name of the first poiType
console.log( console.log(
"Initial poiTypeId set in ShowAddStationPopup.js :", "Initial poiTypeId set in ShowAddStationPopup.js :",
data[0].idPoiTyp data[0].idPoiTyp
@@ -46,44 +46,41 @@ const ShowAddStationPopup = ({ onClose, map, latlng }) => {
} }
}; };
fetchPoiTypData2(); fetchpoiTypData();
}, []); }, []);
//-----------------handleSubmit------------------- //-----------------handleSubmit-------------------
const handleSubmit = async (event) => { const handleSubmit = async (event) => {
event.preventDefault(); event.preventDefault();
const formData = { const formData = {
name, name,
poiTypeId, poiTypeId,
latitude, latitude,
longitude, longitude,
}; };
const response = await fetch("/api/addLocation", { const response = await fetch("/api/addLocation", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify(formData), body: JSON.stringify(formData),
}); });
if (response.ok) { if (response.ok) {
setTrigger((trigger) => { setTrigger((trigger) => {
console.log("Aktueller Trigger-Wert:", trigger); // Vorheriger Wert console.log("Aktueller Trigger-Wert:", trigger); // Vorheriger Wert
const newTrigger = trigger + 1; const newTrigger = trigger + 1;
console.log("Neuer Trigger-Wert:", newTrigger); // Aktualisierter Wert console.log("Neuer Trigger-Wert:", newTrigger); // Aktualisierter Wert
onClose(); onClose();
return newTrigger; return newTrigger;
}); });
} else { } else {
console.error("Fehler beim Hinzufügen des POI"); console.error("Fehler beim Hinzufügen des POI");
} }
if (map && typeof map.closePopup === "function") { if (map && typeof map.closePopup === "function") {
map.closePopup(); map.closePopup();
} }
}; };
return ( return (
<form onSubmit={handleSubmit} className="m-0 p-2 w-full "> <form onSubmit={handleSubmit} className="m-0 p-2 w-full ">
@@ -112,8 +109,8 @@ const handleSubmit = async (event) => {
onChange={(e) => setPoiTypeId(e.target.value)} onChange={(e) => setPoiTypeId(e.target.value)}
className="block p-2 w-full border-2 border-gray-200 rounded-md text-sm" className="block p-2 w-full border-2 border-gray-200 rounded-md text-sm"
> >
{poiTypData2 && {poiTypData &&
poiTypData2.map((poiTyp, index) => ( poiTypData.map((poiTyp, index) => (
<option key={poiTyp.idPoiTyp || index} value={poiTyp.idPoiTyp}> <option key={poiTyp.idPoiTyp || index} value={poiTyp.idPoiTyp}>
{poiTyp.name} {poiTyp.name}
</option> </option>

View File

@@ -23,17 +23,17 @@ if (typeof window !== "undefined") {
user = url.searchParams.get("u") || "484"; // Ein weiterer Parameter aus der URL, Standardwert ist '484 admin zu testen von Stationen ausblenden und einblenden in der Card' user = url.searchParams.get("u") || "484"; // Ein weiterer Parameter aus der URL, Standardwert ist '484 admin zu testen von Stationen ausblenden und einblenden in der Card'
// Konstruktion von URLs, die auf spezifische Ressourcen auf dem Server zeigen // Konstruktion von URLs, die auf spezifische Ressourcen auf dem Server zeigen
/* mapGisStationsStaticDistrictUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsStaticDistrict?idMap=${c}&idUser=${user}`; //idMap: 10, idUser: 484 mapGisStationsStaticDistrictUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsStaticDistrict?idMap=${c}&idUser=${user}`; //idMap: 10, idUser: 484
mapGisStationsStatusDistrictUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsStatusDistrict?idMap=${c}&idUser=${user}`; mapGisStationsStatusDistrictUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsStatusDistrict?idMap=${c}&idUser=${user}`;
mapGisStationsMeasurementsUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsMeasurements?idMap=${c}`; mapGisStationsMeasurementsUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsMeasurements?idMap=${c}`;
mapGisSystemStaticUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisSystemStatic?idMap=${c}&idUser=${user}`; mapGisSystemStaticUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisSystemStatic?idMap=${c}&idUser=${user}`;
mapDataIconUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GetIconsStatic`; */ mapDataIconUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GetIconsStatic`;
mapGisStationsStaticDistrictUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsStaticDistrict`; /* mapGisStationsStaticDistrictUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsStaticDistrict`;
mapGisStationsStatusDistrictUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsStatusDistrict`; mapGisStationsStatusDistrictUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsStatusDistrict`;
mapGisStationsMeasurementsUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsMeasurements`; mapGisStationsMeasurementsUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisStationsMeasurements`;
mapGisSystemStaticUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisSystemStatic`; mapGisSystemStaticUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GisSystemStatic`;
mapDataIconUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GetIconsStatic`; mapDataIconUrl = `${serverURL}/talas5/ClientData/WebserviceMap.asmx/GetIconsStatic`; */
} }
// Export der definierten Variablen und URLs, damit sie in anderen Teilen der Anwendung verwendet werden können // Export der definierten Variablen und URLs, damit sie in anderen Teilen der Anwendung verwendet werden können

View File

@@ -2,8 +2,8 @@
import { createProxyMiddleware } from "http-proxy-middleware"; import { createProxyMiddleware } from "http-proxy-middleware";
export default createProxyMiddleware({ export default createProxyMiddleware({
//target: "http://10.10.0.13", // Ziel-URL des Proxys target: "http://10.10.0.13", // Ziel-URL des Proxys
target: "http://192.168.10.187:3000", // Ziel-URL des Proxys //target: "http://192.168.10.187:3000", // Ziel-URL des Proxys
changeOrigin: true, changeOrigin: true,
pathRewrite: { pathRewrite: {
"^/api": "/", // Optional: Entfernt /api aus dem Pfad, wenn das Backend dies nicht erfordert "^/api": "/", // Optional: Entfernt /api aus dem Pfad, wenn das Backend dies nicht erfordert