POIs hinzufügen, löschen und bearbeiten funktioniert! in mapFeatures.js als marker, irgendwann in poi umbenennen

This commit is contained in:
ISA
2024-08-15 15:53:27 +02:00
parent 18ad7cad7e
commit 8699c1c4a0
10 changed files with 121 additions and 103 deletions

View File

@@ -29,8 +29,8 @@ DB_PORT=3306
NEXT_PUBLIC_BASE_URL="http://10.10.0.70/talas5/devices/"
NEXT_PUBLIC_SERVER_URL="http://10.10.0.70"
NEXT_PUBLIC_PROXY_TARGET="http://10.10.0.70"
#NEXT_PUBLIC_ONLINE_TILE_LAYER="http://10.10.0.13:3000/mapTiles/{z}/{x}/{y}.png"
NEXT_PUBLIC_ONLINE_TILE_LAYER="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
NEXT_PUBLIC_ONLINE_TILE_LAYER="http://10.10.0.13:3000/mapTiles/{z}/{x}/{y}.png"
#NEXT_PUBLIC_ONLINE_TILE_LAYER="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
#########################
#DB_HOST=192.168.10.167

View File

@@ -17,9 +17,7 @@ const PoiUpdateModal = ({ onClose, poiData }) => {
const [idLD, setIdLD] = useState(poiData ? poiData.idLD : "");
const [idLocationDevice, setIdLocationDevice] = useState("");
const [description, setDescription] = useState(
poiData ? poiData.description : ""
);
const [description, setDescription] = useState(poiData ? poiData.description : "");
// Log the initial POI data
useEffect(() => {
@@ -65,16 +63,11 @@ const PoiUpdateModal = ({ onClose, poiData }) => {
const fetchDeviceId = async () => {
if (poiData && poiData.idLD) {
try {
const response = await fetch(
`/api/talas_v5_DB/locationDevice/getDeviceIdById?idLD=${poiData.idLD}`
);
const response = await fetch(`/api/talas_v5_DB/locationDevice/getDeviceIdById?idLD=${poiData.idLD}`);
const data = await response.json();
if (data) setDeviceName(data.name);
} catch (error) {
console.error(
"Fehler beim Abrufen der Geräteinformation in PoiUpdateModel.js: ",
error
);
console.error("Fehler beim Abrufen der Geräteinformation in PoiUpdateModel.js: ", error);
}
}
};
@@ -86,12 +79,9 @@ const PoiUpdateModal = ({ onClose, poiData }) => {
const handleDeletePoi = async () => {
if (confirm("Sind Sie sicher, dass Sie diesen POI löschen möchten?")) {
try {
const response = await fetch(
`/api/talas_v5_DB/pois/deletePoi?id=${poiId}`,
{
method: "DELETE",
}
);
const response = await fetch(`/api/talas_v5_DB/pois/deletePoi?id=${poiId}`, {
method: "DELETE",
});
if (response.ok) {
alert("POI wurde erfolgreich gelöscht.");
onClose(); // Close the modal
@@ -101,7 +91,7 @@ const PoiUpdateModal = ({ onClose, poiData }) => {
throw new Error("Fehler beim Löschen des POI.");
}
} catch (error) {
console.error("Fehler beim Löschen des POI:", error);
console.error("Fehler beim Löschen des POI 1:", error);
alert("Fehler beim Löschen des POI.");
}
}
@@ -137,18 +127,13 @@ const PoiUpdateModal = ({ onClose, poiData }) => {
setLocationDeviceData(data);
console.log("Standort- und Gerätedaten poiData:", poiData);
if (poiData && poiData.idLD) {
const selectedDevice = data.find(
(device) => device.id === poiData.idLD
);
const selectedDevice = data.find((device) => device.id === poiData.idLD);
setDeviceName(selectedDevice ? selectedDevice.id : data[0].id); // Hier wird die ID als initialer Zustand gesetzt
console.log("Selected Device:", selectedDevice);
console.log("Selected devciceName:", deviceName);
}
} catch (error) {
console.error(
"Fehler beim Abrufen der Standort- und Gerätedaten:",
error
);
console.error("Fehler beim Abrufen der Standort- und Gerätedaten:", error);
}
};
fetchData();
@@ -165,9 +150,7 @@ const PoiUpdateModal = ({ onClose, poiData }) => {
console.log("Standort- und Gerätedaten 3:", data);
console.log("Standort- und Gerätedaten 3 poiData:", poiData);
// Findet das Gerät, das der aktuellen IDLD entspricht
const currentDevice = data.find(
(device) => device.idLD === currentPoi.idLD
);
const currentDevice = data.find((device) => device.idLD === currentPoi.idLD);
if (currentDevice) {
setDeviceName(currentDevice.name);
}
@@ -184,9 +167,7 @@ const PoiUpdateModal = ({ onClose, poiData }) => {
const handleSubmit = async (event) => {
event.preventDefault();
const idLDResponse = await fetch(
`/api/talas_v5_DB/locationDevice/getDeviceId?deviceName=${encodeURIComponent(deviceName)}`
);
const idLDResponse = await fetch(`/api/talas_v5_DB/locationDevice/getDeviceId?deviceName=${encodeURIComponent(deviceName)}`);
const idLDData = await idLDResponse.json();
const idLD = idLDData.idLD;
try {
@@ -210,9 +191,7 @@ const PoiUpdateModal = ({ onClose, poiData }) => {
window.location.reload();
} else {
const errorResponse = await response.json();
throw new Error(
errorResponse.error || "Fehler beim Aktualisieren des POI."
);
throw new Error(errorResponse.error || "Fehler beim Aktualisieren des POI.");
}
} catch (error) {
console.error("Fehler beim Aktualisieren des POI:", error);
@@ -224,14 +203,8 @@ const PoiUpdateModal = ({ onClose, poiData }) => {
console.log("Selected POI:", selectedPoi);
console.log("Selected POI Gerät id in poiUpdateModal.js:", selectedPoi.id);
console.log("Selected POI Typ name in poiUpdateModal.js:", selectedPoi.typ); //als Typ in dropdown menu
console.log(
"Selected POI Beschreibung in poiUpdateModal.js:",
selectedPoi.description
);
console.log(
"Selected POI Gerät deviceId in poiUpdateModal.js:",
selectedPoi.deviceId
);
console.log("Selected POI Beschreibung in poiUpdateModal.js:", selectedPoi.description);
console.log("Selected POI Gerät deviceId in poiUpdateModal.js:", selectedPoi.deviceId);
return (
<form onSubmit={handleSubmit} className="m-0 p-2 w-full">
@@ -239,28 +212,14 @@ const PoiUpdateModal = ({ onClose, poiData }) => {
<label htmlFor="description" className="block mr-2 flex-none">
Beschreibung:
</label>
<input
type="text"
id="description"
name="description"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="Beschreibung der Station"
className="block p-2 w-full border-2 border-gray-200 rounded-md text-sm"
/>
<input type="text" id="description" name="description" value={description} onChange={(e) => setDescription(e.target.value)} placeholder="Beschreibung der Station" className="block p-2 w-full border-2 border-gray-200 rounded-md text-sm" />
</div>
<div className="flex items-center mb-4">
<label htmlFor="deviceName" className="block mr-2 flex-none">
Gerät:
</label>
<select
id="deviceName"
name="deviceName"
value={deviceName}
onChange={(e) => setDeviceName(e.target.value)}
className="block p-2 w-full border-2 border-gray-200 rounded-md text-sm"
>
<select id="deviceName" name="deviceName" value={deviceName} onChange={(e) => setDeviceName(e.target.value)} className="block p-2 w-full border-2 border-gray-200 rounded-md text-sm">
{locationDeviceData.map(
(device, index) => (
console.log("device.id und name:", device),
@@ -278,13 +237,7 @@ const PoiUpdateModal = ({ onClose, poiData }) => {
<label htmlFor="idPoiTyp2" className="block mr-2 flex-none">
Typ:
</label>
<select
id="idPoiTyp2"
name="idPoiTyp2"
value={poiTypeId}
onChange={(e) => setPoiTypeId(e.target.value)}
className="block p-2 w-full border-2 border-gray-200 rounded-md text-sm"
>
<select id="idPoiTyp2" name="idPoiTyp2" value={poiTypeId} onChange={(e) => setPoiTypeId(e.target.value)} className="block p-2 w-full border-2 border-gray-200 rounded-md text-sm">
{poiTypData.map((poiTyp, index) => (
<option key={index} value={poiTyp.idPoiTyp}>
{poiTyp.name}
@@ -301,10 +254,7 @@ const PoiUpdateModal = ({ onClose, poiData }) => {
POI löschen
</button>
<button
type="submit"
className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded w-full"
>
<button type="submit" className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded w-full">
POI aktualisieren
</button>
</form>

View File

@@ -61,7 +61,7 @@ const PoiUpdateModal = ({ onClose, poiData, onSubmit }) => {
throw new Error("Fehler beim Löschen des POI.");
}
} catch (error) {
console.error("Fehler beim Löschen des POI:", error);
console.error("Fehler beim Löschen des POI 2:", error);
alert("Fehler beim Löschen des POI.");
}
}

View File

@@ -25,7 +25,7 @@ const useLineData = (webserviceGisLinesStatusUrl, setLineStatusData) => {
// Sortiere die Meldungen nach Level, damit die höchste Priorität (kleinster Level) zuerst kommt
const sortedStatis = [...data1.Statis].sort((a, b) => a.Level - b.Level);
console.log("Sortierte Daten:", sortedStatis);
//console.log("Sortierte Daten:", sortedStatis);
// Filtere Objekte mit gleichem IdLD und Modul, und Level > 0, und entferne die Objekte mit dem höchsten Level
const filteredStatis = [];
@@ -45,7 +45,7 @@ const useLineData = (webserviceGisLinesStatusUrl, setLineStatusData) => {
}
});
console.log("Gefilterte Daten (Objekte mit höchstem Level entfernt):", filteredStatis);
//console.log("Gefilterte Daten (Objekte mit höchstem Level entfernt):", filteredStatis);
filteredStatis.forEach((statis) => {
const key = `${statis.IdLD}-${statis.Modul}`;

View File

@@ -33,7 +33,7 @@ export default function handler(req, res) {
const query = "DELETE FROM poi WHERE idPoi = ?";
connection.query(query, [id], (error, results) => {
if (error) {
console.error("Fehler beim Löschen des POI:", error);
console.error("Fehler beim Löschen des POI 4:", error);
return res.status(500).json({ error: "Fehler beim Löschen des POI" });
}
if (results.affectedRows > 0) {

View File

@@ -36,7 +36,7 @@ export default async function handler(req, res) {
res.status(404).json({ error: "POI nicht gefunden" });
}
} catch (error) {
console.error("Fehler beim Löschen des POI:", error);
console.error("Fehler beim Löschen des POI 3:", error);
res.status(500).json({ error: "Fehler beim Löschen des POI" });
}
}

View File

@@ -1,33 +1,40 @@
// contextMenuUtils.js
import { BASE_URL } from "../config/urls";
export function addContextMenuToMarker(marker) {
marker.unbindContextMenu(); // Entferne das Kontextmenü, um Duplikate zu vermeiden
marker.bindContextMenu({
contextmenu: true,
contextmenuWidth: 140,
contextmenuItems: [
/* {
text: "Station öffnen (Tab)",
icon: "/img/screen_new.png",
callback: (e) => openInNewTab(e, marker),
},
{
text: "Station öffnen",
icon: "/img/screen_same.png",
callback: (e) => openInSameWindow(e, marker),
}, */
],
contextmenuItems: [],
});
}
// Funktion zum Öffnen in einem neuen Tab
export function openInNewTab(e, marker) {
export function openInNewTab(e, target) {
const baseUrl = BASE_URL;
//console.log("baseUrl:", baseUrl);
if (marker && marker.options && marker.options.link) {
//console.log("Marker data:", baseUrl + marker.options.link);
window.open(baseUrl + marker.options.link, "_blank");
let idLD, idModul, link;
if (target instanceof L.Polyline) {
idLD = target.options.idLD;
idModul = target.options.idModul;
if (idLD) {
link = `${baseUrl}/talas5/devices/cpl.aspx?id=${idLD}`;
if (idModul) {
//link += `&module=${idModul}`;
}
} else {
console.error("Keine gültige 'idLD' für die Linie gefunden.");
return;
}
} else if (target instanceof L.Marker && target.options.link) {
link = baseUrl + target.options.link;
} else {
console.error("Fehler: Marker hat keine gültige 'link' Eigenschaft");
console.error("Fehler: Ungültiges Ziel oder keine gültige 'link' Eigenschaft.");
return;
}
// Öffne den Link in einem neuen Tab
window.open(link, "_blank");
}

View File

@@ -17,3 +17,37 @@ export const findClosestPoints = (coordinates, newPoint, map) => {
}
return closestPair;
};
// Hilfsfunktion zur Berechnung der Entfernung zwischen zwei Punkten (LatLng)
export function getDistance(latlng1, latlng2) {
const R = 6371e3; // Erdradius in Metern
const lat1 = latlng1.lat * (Math.PI / 180);
const lat2 = latlng2.lat * (Math.PI / 180);
const deltaLat = (latlng2.lat - latlng1.lat) * (Math.PI / 180);
const deltaLng = (latlng2.lng - latlng1.lng) * (Math.PI / 180);
const a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) + Math.cos(lat1) * Math.cos(lat2) * Math.sin(deltaLng / 2) * Math.sin(deltaLng / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c; // Entfernung in Metern
}
// Funktion zum Finden der nächsten Linie basierend auf der Mausposition
export function findNearestPolyline(map, mouseLatLng) {
let nearestPolyline = null;
let minDistance = Infinity;
map.eachLayer(function (layer) {
if (layer instanceof L.Polyline) {
const latlngs = layer.getLatLngs();
latlngs.forEach((latlng) => {
const distance = getDistance(mouseLatLng, latlng);
if (distance < minDistance) {
minDistance = distance;
nearestPolyline = layer;
}
});
}
});
return nearestPolyline;
}

View File

@@ -58,7 +58,7 @@ export const setupMarkers = async (
popupAnchor: [1, -34],
}),
draggable: canDrag,
idLD: location.idLD, // Füge die idLD zum Marker hinzu
id: location.idPoi,
name: location.name,
description: location.description,
}).bindContextMenu({
@@ -165,7 +165,6 @@ export const setupPolylines = (map, linePositions, lineColors, tooltipContents,
};
//document.addEventListener("mousedown", handleOutsideClick);
linePositions.forEach((lineData, lineIndex) => {
const lineMarkers = [];
lineData.coordinates.forEach((coord, index) => {
@@ -319,6 +318,5 @@ export const setupPolylines = (map, linePositions, lineColors, tooltipContents,
// Add listeners to the context menu items
const contextMenuElement = document.querySelector(".leaflet-contextmenu"); // Assuming the context menu class is 'leaflet-contextmenu'
return { markers, polylines };
};

View File

@@ -1,18 +1,18 @@
// /utils/mapInitialization.js
import L from "leaflet";
//import OverlappingMarkerSpiderfier from "overlapping-marker-spiderfier-leaflet";
import "leaflet-contextmenu";
import "leaflet/dist/leaflet.css";
import "leaflet-contextmenu/dist/leaflet.contextmenu.css";
import * as urls from "../config/urls.js";
import * as layers from "../config/layers.js";
import { addContextMenuToMarker, openInNewTab } from "../utils/contextMenuUtils.js";
import { openInNewTab } from "../utils/contextMenuUtils.js";
import { findNearestPolyline } from "./geometryUtils"; // Importiere die Funktion zur Suche der nächsten Linie
let lastClickedTarget = null; // Variable zur Zwischenspeicherung des Ziels
export const initializeMap = (mapRef, setMap, setOms, setMenuItemAdded, addItemsToMapContextMenu, hasRights) => {
const offlineTileLayer = urls.OFFLINE_TILE_LAYER;
//const offlineTileLayer = process.env.OFFLINE_TILE_LAYER;
const onlineTileLayer = urls.ONLINE_TILE_LAYER;
//const onlineTileLayer = process.env.ONLINE_TILE_LAYER;
const TALAS = layers.MAP_LAYERS.TALAS;
const ECI = layers.MAP_LAYERS.ECI;
const ULAF = layers.MAP_LAYERS.ULAF;
@@ -37,11 +37,15 @@ export const initializeMap = (mapRef, setMap, setOms, setMenuItemAdded, addItems
contextmenu: true,
contextmenuItems: [
{
text: "Station öffnen (Tab)",
text: "Station Öffnen (Tab)",
icon: "/img/screen_new.png",
callback: (e) => {
const clickedMarker = e.relatedTarget;
openInNewTab(e, clickedMarker);
const clickedTarget = lastClickedTarget || findNearestPolyline(initMap, e.latlng); // Verwende zwischengespeichertes Ziel oder die nächstgelegene Linie
if (clickedTarget) {
openInNewTab(e, clickedTarget); // Gemeinsame Funktion für Linien und Stationen
} else {
console.error("Kein gültiges Ziel im Kontextmenü");
}
},
},
"-",
@@ -67,6 +71,31 @@ export const initializeMap = (mapRef, setMap, setOms, setMenuItemAdded, addItems
}
});
// Speichere das Ziel, wenn die Maus über eine Linie oder einen Marker fährt
initMap.on("mouseover", function (e) {
if (e.layer instanceof L.Polyline || e.layer instanceof L.Marker) {
lastClickedTarget = e.layer; // Speichere das zuletzt überfahrene Element
}
});
// Kontextmenü-Event
initMap.on("contextmenu", function (e) {
const clickedTarget = lastClickedTarget || findNearestPolyline(initMap, e.latlng) || e.relatedTarget || e.layer; // Verwende entweder das zwischengespeicherte Ziel oder die nächstgelegene Linie
if (!clickedTarget) {
console.error("Kein gültiges Ziel im Kontextmenü");
return;
}
if (clickedTarget instanceof L.Polyline) {
console.log("ID der Linie (idLD):", clickedTarget.options.idLD);
// Das Kontextmenü wird nun geöffnet und beim Klicken wird `openInNewTab` ausgeführt
} else if (clickedTarget instanceof L.Marker) {
openInNewTab(e, clickedTarget);
} else {
console.error("Fehler: Ungültiges Ziel.");
}
});
initMap.whenReady(() => {
console.log("Karte ist jetzt bereit und initialisiert.");
addItemsToMapContextMenu(hasRights);