Merge branch 'develop'
This commit is contained in:
11
utils/addContextMenuToMarker.js
Normal file
11
utils/addContextMenuToMarker.js
Normal file
@@ -0,0 +1,11 @@
|
||||
// /utils/addContextMenuToMarker.js
|
||||
|
||||
export function addContextMenuToMarker(marker) {
|
||||
marker.unbindContextMenu(); // Entferne das Kontextmenü, um Duplikate zu vermeiden
|
||||
|
||||
marker.bindContextMenu({
|
||||
contextmenu: true,
|
||||
contextmenuWidth: 140,
|
||||
contextmenuItems: [],
|
||||
});
|
||||
}
|
||||
123
utils/createAndSetDevices.js
Normal file
123
utils/createAndSetDevices.js
Normal file
@@ -0,0 +1,123 @@
|
||||
// /utils/createAndSetDevices.js
|
||||
import circleIcon from "../components/gisPolylines/icons/CircleIcon";
|
||||
import { saveLineData, redrawPolyline } from "./mapUtils";
|
||||
import L from "leaflet";
|
||||
import "leaflet.smooth_marker_bouncing";
|
||||
import { toast } from "react-toastify";
|
||||
import * as config from "../config/config.js";
|
||||
import { disablePolylineEvents, enablePolylineEvents } from "./setupPolylines"; // Importiere die Funktion zum Deaktivieren der Polyline-Ereignisse
|
||||
import { setPolylineEventsDisabled } from "../store/atoms/polylineEventsDisabledState"; // Importiere den Recoil-Atom-Zustand
|
||||
|
||||
// Funktion zum Bestimmen der Priorität basierend auf dem Icon-Pfad
|
||||
const determinePriority = (iconPath, priorityConfig) => {
|
||||
for (let priority of priorityConfig) {
|
||||
if (iconPath.includes(priority.name.toLowerCase())) {
|
||||
return priority.level;
|
||||
}
|
||||
}
|
||||
return 5; // Standardpriorität (niedrigste)
|
||||
};
|
||||
|
||||
// Funktion zum Erstellen und Setzen von Markern
|
||||
export const createAndSetDevices = async (systemId, setMarkersFunction, GisSystemStatic, priorityConfig) => {
|
||||
try {
|
||||
// Zähler für externe API-Aufrufe in localStorage speichern
|
||||
let requestCount = localStorage.getItem("gisStationsStaticRequestCount-createDevice") || 0;
|
||||
requestCount++;
|
||||
localStorage.setItem("gisStationsStaticRequestCount-createDevice", requestCount);
|
||||
//console.log(`config.mapGisStationsStaticDistrictUrl in createAndSetDevice wurde ${requestCount} Mal aufgerufen.`);
|
||||
|
||||
const response1 = await fetch(config.mapGisStationsStaticDistrictUrl);
|
||||
const jsonResponse = await response1.json();
|
||||
const response2 = await fetch(config.mapGisStationsStatusDistrictUrl);
|
||||
const statusResponse = await response2.json();
|
||||
const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;
|
||||
|
||||
const getIdSystemAndAllowValueMap = new Map(GisSystemStatic.map((system) => [system.IdSystem, system.Allow]));
|
||||
|
||||
if (jsonResponse.Points && statusResponse.Statis) {
|
||||
console.log("jsonResponse.Points: ", jsonResponse.Points);
|
||||
console.log("statusResponse.Statis: ", statusResponse.Statis);
|
||||
const statisMap = new Map(statusResponse.Statis.map((s) => [s.IdLD, s]));
|
||||
let markersData = jsonResponse.Points.filter((station) => station.System === systemId && getIdSystemAndAllowValueMap.get(station.System) === 1).map((station) => {
|
||||
const statis = statisMap.get(station.IdLD);
|
||||
const iconPath = statis ? `img/icons/${statis.Na}-marker-icon-${station.Icon}.png` : `img/icons/marker-icon-${station.Icon}.png`;
|
||||
|
||||
const priority = determinePriority(iconPath, priorityConfig);
|
||||
const zIndexOffset = 100 * (5 - priority); // Adjusted for simplicity and positive values
|
||||
|
||||
const marker = L.marker([station.X, station.Y], {
|
||||
icon: L.icon({
|
||||
iconUrl: iconPath,
|
||||
iconSize: [25, 41],
|
||||
iconAnchor: [12, 41],
|
||||
popupAnchor: [1, -34],
|
||||
}),
|
||||
areaName: station.Area_Name, // Stelle sicher, dass dieser Bereich gesetzt wird
|
||||
link: station.Link,
|
||||
zIndexOffset: zIndexOffset,
|
||||
});
|
||||
|
||||
// Deaktiviere Polyline-Ereignisse beim Überfahren des Markers
|
||||
marker.on("mouseover", function () {
|
||||
this.openPopup();
|
||||
});
|
||||
|
||||
// Verwende das `contextmenu`-Ereignis für den Rechtsklick
|
||||
|
||||
marker.on("contextmenu", function (event) {
|
||||
if (event && event.preventDefault) {
|
||||
event.preventDefault(); // Verhindert das Standard-Kontextmenü
|
||||
}
|
||||
//setPolylineEventsDisabled(true);
|
||||
//disablePolylineEvents(window.polylines);
|
||||
this.openPopup();
|
||||
});
|
||||
|
||||
document.addEventListener("mouseout", function (event) {
|
||||
if (event.relatedTarget === null || event.relatedTarget.nodeName === "BODY") {
|
||||
//setPolylineEventsDisabled(false);
|
||||
enablePolylineEvents(window.polylines, window.lineColors);
|
||||
}
|
||||
});
|
||||
marker.on("mouseout", function () {
|
||||
this.closePopup();
|
||||
});
|
||||
|
||||
// Überprüfe, ob die bounce-Funktion verfügbar ist und verwende sie
|
||||
if (typeof marker.bounce === "function" && statis) {
|
||||
marker.on("add", () => marker.bounce(3));
|
||||
}
|
||||
|
||||
const statusInfo = statusResponse.Statis.filter((status) => status.IdLD === station.IdLD)
|
||||
.reverse()
|
||||
.map(
|
||||
(status) => `
|
||||
<div class="flex items-center my-1">
|
||||
<div class="w-2 h-2 mr-2 inline-block rounded-full" style="background-color: ${status.Co};"></div>
|
||||
${status.Me} <span style="color: ${status.Co};">(${status.Na})</span>
|
||||
</div>
|
||||
`
|
||||
)
|
||||
.join("");
|
||||
|
||||
marker.bindPopup(`
|
||||
<div class="bg-white rounded-lg">
|
||||
<span class="text-lg font-semibold text-gray-900">${station.LD_Name}</span>
|
||||
<span class="text-md font-bold text-gray-800"> ${station.Device}</span><br>
|
||||
<span class="text-gray-800"><strong> ${station.Area_Short} </strong>(${station.Area_Name})</span><br>
|
||||
<span class="text-gray-800"><strong>${station.Location_Short} </strong> (${station.Location_Name})</span>
|
||||
<div class="mt-2">${statusInfo}</div>
|
||||
</div>
|
||||
`);
|
||||
|
||||
|
||||
return marker;
|
||||
});
|
||||
|
||||
setMarkersFunction(markersData);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching data: ", error);
|
||||
}
|
||||
};
|
||||
@@ -1,17 +1,32 @@
|
||||
// utils/geometryUtils.js
|
||||
|
||||
/**
|
||||
* Parses a point string in the format "POINT (longitude latitude)" and returns an object with latitude and longitude as numbers.
|
||||
* @param {string} position - The position string in the format "POINT (longitude latitude)".
|
||||
* @returns {{latitude: number, longitude: number}} An object containing the latitude and longitude as numbers.
|
||||
*/
|
||||
export const parsePoint = (position) => {
|
||||
const [longitude, latitude] = position.slice(6, -1).split(" ");
|
||||
return { latitude: parseFloat(latitude), longitude: parseFloat(longitude) };
|
||||
};
|
||||
|
||||
/**
|
||||
* Finds the closest points on a polyline to a new point.
|
||||
* @param {Array} coordinates - The coordinates of the polyline.
|
||||
* @param {Object} newPoint - The new point (with latitude and longitude).
|
||||
* @param {Object} map - The map object.
|
||||
* @returns {Array} The closest pair of points on the polyline.
|
||||
*/
|
||||
export const findClosestPoints = (coordinates, newPoint, map) => {
|
||||
if (!map) {
|
||||
console.error("Map is not defined. Cannot find closest points.");
|
||||
return [];
|
||||
}
|
||||
|
||||
let minDist = Infinity;
|
||||
let closestPair = [];
|
||||
for (let i = 1; i < coordinates.length; i++) {
|
||||
const dist = L.LineUtil.pointToSegmentDistance(
|
||||
map.latLngToLayerPoint(newPoint),
|
||||
map.latLngToLayerPoint(coordinates[i - 1]),
|
||||
map.latLngToLayerPoint(coordinates[i])
|
||||
);
|
||||
const dist = L.LineUtil.pointToSegmentDistance(map.latLngToLayerPoint(newPoint), map.latLngToLayerPoint(coordinates[i - 1]), map.latLngToLayerPoint(coordinates[i]));
|
||||
if (dist < minDist) {
|
||||
minDist = dist;
|
||||
closestPair = [coordinates[i - 1], coordinates[i], i];
|
||||
@@ -19,3 +34,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;
|
||||
}
|
||||
|
||||
37
utils/handlePoiSelect.js
Normal file
37
utils/handlePoiSelect.js
Normal file
@@ -0,0 +1,37 @@
|
||||
// utils/handlePoiSelect.js
|
||||
const handlePoiSelect = async (poiData, setSelectedPoi, setLocationDeviceData, setDeviceName, poiLayerRef, poiTypMap) => {
|
||||
setSelectedPoi(poiData); // Setzt das ausgewählte POI
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/talas_v5_DB/locationDevice/locationDevices");
|
||||
const data = await response.json();
|
||||
setLocationDeviceData(data);
|
||||
|
||||
const currentDevice = data.find((device) => device.idLD === poiData.deviceId);
|
||||
if (currentDevice) {
|
||||
setDeviceName(currentDevice.name);
|
||||
|
||||
// Hier speichern wir den POI-Typ im localStorage
|
||||
const poiTypeName = poiTypMap.get(poiData.idPoiTyp);
|
||||
localStorage.setItem("selectedPoiType", poiTypeName);
|
||||
|
||||
// Optional: Update des Markers mit dem POI-Typ
|
||||
const marker = poiLayerRef.current.getLayers().find((m) => m.options.id === poiData.id);
|
||||
if (marker) {
|
||||
marker.setPopupContent(`
|
||||
<div>
|
||||
<b class="text-xl text-black-700">${poiData.description || "Unbekannt"}</b><br>
|
||||
${currentDevice.name}<br>
|
||||
${poiTypeName || "Unbekannt"}<br>
|
||||
</div>
|
||||
`);
|
||||
marker.openPopup();
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Fehler beim Abrufen der Gerätedaten:", error);
|
||||
setLocationDeviceData([]);
|
||||
}
|
||||
};
|
||||
|
||||
export default handlePoiSelect;
|
||||
73
utils/initializeMap.js
Normal file
73
utils/initializeMap.js
Normal file
@@ -0,0 +1,73 @@
|
||||
// utils/initializeMap.js
|
||||
import L from "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 { openInNewTab } from "./openInNewTab.js";
|
||||
|
||||
export const initializeMap = (mapRef, setMap, setOms, setMenuItemAdded, addItemsToMapContextMenu, hasRights, setPolylineEventsDisabled) => {
|
||||
if (mapRef.current) {
|
||||
const initMap = L.map(mapRef.current, {
|
||||
center: [53.111111, 8.4625],
|
||||
zoom: 12,
|
||||
layers: [layers.MAP_LAYERS.TALAS, layers.MAP_LAYERS.ECI, layers.MAP_LAYERS.ULAF, layers.MAP_LAYERS.GSMModem],
|
||||
minZoom: 5,
|
||||
maxZoom: 15,
|
||||
zoomControl: false,
|
||||
contextmenu: true,
|
||||
contextmenuItems: [
|
||||
{
|
||||
text: "Station öffnen (Tab)",
|
||||
icon: "/img/screen_new.png",
|
||||
callback: (e) => {
|
||||
const link = localStorage.getItem("polylineLink");
|
||||
const clickedElement = e.relatedTarget;
|
||||
|
||||
// Überprüfe, ob Karte und contextmenu existieren
|
||||
if (initMap && initMap.contextmenu) {
|
||||
// Verarbeite Kontextmenü-Callback
|
||||
if (link) {
|
||||
const newTab = window.open(link, "_blank");
|
||||
if (newTab) {
|
||||
// Lösche Einträge im localStorage
|
||||
localStorage.removeItem("polylineLink");
|
||||
localStorage.removeItem("lastElementType");
|
||||
} else {
|
||||
console.error("Fehler: Das neue Tab konnte nicht geöffnet werden.");
|
||||
}
|
||||
} else if (clickedElement instanceof L.Marker || clickedElement instanceof L.Polyline) {
|
||||
openInNewTab(e, clickedElement);
|
||||
} else {
|
||||
console.error("Kein gültiges Ziel für den Kontextmenüeintrag");
|
||||
}
|
||||
} else {
|
||||
console.error("Karte oder Kontextmenü nicht verfügbar.");
|
||||
}
|
||||
},
|
||||
},
|
||||
"-",
|
||||
],
|
||||
});
|
||||
|
||||
// Füge die Tile-Layer hinzu
|
||||
L.tileLayer(urls.ONLINE_TILE_LAYER, {
|
||||
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
|
||||
}).addTo(initMap);
|
||||
|
||||
// Initialisiere OverlappingMarkerSpiderfier
|
||||
const overlappingMarkerSpiderfier = new OverlappingMarkerSpiderfier(initMap, {
|
||||
nearbyDistance: 20,
|
||||
});
|
||||
|
||||
// Setze die Map und OMS in den State
|
||||
setMap(initMap);
|
||||
setOms(overlappingMarkerSpiderfier);
|
||||
|
||||
// Wenn Rechte geladen sind und es noch nicht hinzugefügt wurde, füge das Kontextmenü hinzu
|
||||
if (hasRights && !setMenuItemAdded) {
|
||||
addItemsToMapContextMenu(initMap, setMenuItemAdded, setPolylineEventsDisabled);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -13,8 +13,7 @@ export const redrawPolyline = (lineData, lineColors, tooltipContents, map) => {
|
||||
}
|
||||
|
||||
const color = lineColors[lineData.idModul] || "#000000";
|
||||
const tooltipContent =
|
||||
tooltipContents[lineData.idModul] || "Standard-Tooltip-Inhalt";
|
||||
const tooltipContent = tooltipContents[lineData.idModul] || "Standard-Tooltip-Inhalt";
|
||||
|
||||
if (lineData.polyline) map.removeLayer(lineData.polyline);
|
||||
|
||||
@@ -56,7 +55,7 @@ export const saveLineData = (lineData) => {
|
||||
return response.json();
|
||||
})
|
||||
.then((data) => {
|
||||
console.log("Linienänderungen gespeichert:", data);
|
||||
//console.log("Linienänderungen gespeichert:", data);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Fehler beim Speichern der Linienänderungen:", error);
|
||||
@@ -82,7 +81,7 @@ export const restoreMapSettings = (map) => {
|
||||
export const checkOverlappingMarkers = (map, markers, plusIcon) => {
|
||||
// Ensure markers is always an array
|
||||
if (!Array.isArray(markers)) {
|
||||
//console.error("The `markers` argument is not an array:", markers);
|
||||
console.error("The `markers` argument is not an array:", markers);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -105,7 +104,8 @@ export const checkOverlappingMarkers = (map, markers, plusIcon) => {
|
||||
const plusMarker = L.marker(latLng, { icon: plusIcon });
|
||||
plusMarker.addTo(map);
|
||||
|
||||
//console.log("Adding plus icon marker at", latLng);
|
||||
console.log("Adding plus icon marker at", latLng);
|
||||
}
|
||||
}
|
||||
console.log("overlappingGroups", overlappingGroups);
|
||||
};
|
||||
|
||||
52
utils/mysqlPool.js
Normal file
52
utils/mysqlPool.js
Normal file
@@ -0,0 +1,52 @@
|
||||
import mysql from "mysql2/promise";
|
||||
// Variablen für den Singleton-Pool
|
||||
let cachedPool;
|
||||
let connectionCount = 0; // Zähler für die aktiven Verbindungen
|
||||
|
||||
// Funktion zum Abrufen des Pools
|
||||
function getPool() {
|
||||
if (!cachedPool) {
|
||||
cachedPool = mysql.createPool({
|
||||
host: process.env.DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.DB_NAME,
|
||||
port: process.env.DB_PORT,
|
||||
connectionLimit: 20, // Setze ein Limit für gleichzeitige Verbindungen
|
||||
waitForConnections: true,
|
||||
queueLimit: 10, // Warteschlangenlimit für Verbindungen
|
||||
connectTimeout: 5000, // Timeout für Verbindungsversuche (5 Sekunden)
|
||||
acquireTimeout: 10000, // Timeout für Verbindungsanforderungen aus dem Pool (10 Sekunden)
|
||||
idleTimeout: 60000, // 1 Minute
|
||||
});
|
||||
|
||||
// Ereignisse für das Protokollieren der Verbindungsstatistiken
|
||||
cachedPool.on("acquire", () => {
|
||||
connectionCount++;
|
||||
console.log(`[ACQUIRE] Active connections: ${connectionCount}`);
|
||||
});
|
||||
|
||||
cachedPool.on("release", () => {
|
||||
connectionCount--;
|
||||
console.log(`[RELEASE] Active connections: ${connectionCount}`);
|
||||
});
|
||||
|
||||
cachedPool.on("enqueue", () => {
|
||||
console.log(`[ENQUEUE] Waiting for available connection slot.`);
|
||||
});
|
||||
}
|
||||
|
||||
return cachedPool;
|
||||
}
|
||||
|
||||
// Optionale Funktion zum Schließen aller Verbindungen im Pool (manuell aufzurufen)
|
||||
export function closePool() {
|
||||
if (cachedPool) {
|
||||
cachedPool.end(() => {
|
||||
console.log("All pool connections closed.");
|
||||
});
|
||||
cachedPool = null; // Setze den Pool auf null, um sicherzustellen, dass er neu erstellt wird, falls benötigt.
|
||||
}
|
||||
}
|
||||
|
||||
export default getPool;
|
||||
38
utils/openInNewTab.js
Normal file
38
utils/openInNewTab.js
Normal file
@@ -0,0 +1,38 @@
|
||||
// utils/openInNewTab.js
|
||||
|
||||
export function openInNewTab(e, target) {
|
||||
const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;
|
||||
let link;
|
||||
|
||||
// Prüfen, ob der Kontextmenü-Eintrag aufgerufen wird, ohne dass ein Marker oder Polyline direkt angesprochen wird
|
||||
if (!target) {
|
||||
// Verwende den in localStorage gespeicherten Link
|
||||
const lastElementType = localStorage.getItem("lastElementType");
|
||||
if (lastElementType === "polyline") {
|
||||
link = localStorage.getItem("polylineLink");
|
||||
}
|
||||
}
|
||||
|
||||
if (target instanceof L.Marker && target.options.link) {
|
||||
link = `${BASE_URL}${target.options.link}`;
|
||||
} else if (target instanceof L.Polyline) {
|
||||
const idLD = target.options.idLD;
|
||||
console.log("idLD der Linie", idLD);
|
||||
if (idLD) {
|
||||
link = `${BASE_URL}cpl.aspx?id=${idLD}`;
|
||||
} else {
|
||||
console.error("Keine gültige 'idLD' für die Linie gefunden.");
|
||||
return;
|
||||
}
|
||||
} else if (!link) {
|
||||
console.error("Fehler: Es wurde kein gültiger Link gefunden.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Öffne den Link in einem neuen Tab
|
||||
if (link) {
|
||||
window.open(link, "_blank");
|
||||
} else {
|
||||
console.error("Fehler: Es wurde kein gültiger Link gefunden.");
|
||||
}
|
||||
}
|
||||
119
utils/poiUtils.js
Normal file
119
utils/poiUtils.js
Normal file
@@ -0,0 +1,119 @@
|
||||
// /utils/poiUtils.js
|
||||
import circleIcon from "../components/gisPolylines/icons/CircleIcon.js";
|
||||
import { saveLineData, redrawPolyline } from "./mapUtils.js";
|
||||
import L from "leaflet";
|
||||
import "leaflet.smooth_marker_bouncing";
|
||||
import { toast } from "react-toastify";
|
||||
import * as config from "../config/config.js";
|
||||
|
||||
export const insertNewPOI = (closestPoints, newPoint, lineData, map) => {
|
||||
const newMarker = L.marker(newPoint, {
|
||||
icon: circleIcon,
|
||||
draggable: true,
|
||||
}).addTo(map);
|
||||
lineData.coordinates.splice(closestPoints[2], 0, [newPoint.lat, newPoint.lng]);
|
||||
|
||||
// Hier direkt speichern nach Einfügen
|
||||
saveLineData(lineData);
|
||||
|
||||
redrawPolyline(lineData);
|
||||
|
||||
// Event-Listener für das Verschieben des Markers hinzufügen
|
||||
newMarker.on("dragend", () => {
|
||||
console.log("Marker wurde verschoben in insertNewPOI");
|
||||
const newCoords = newMarker.getLatLng();
|
||||
setNewCoords(newCoords);
|
||||
const newCoordinates = [...lineData.coordinates];
|
||||
newCoordinates[closestPoints[2]] = [newCoords.lat, newCoords.lng];
|
||||
lineData.coordinates = newCoordinates;
|
||||
redrawPolyline(lineData);
|
||||
|
||||
updateMarkerPosition(newMarker.getLatLng(), lineData, newMarker);
|
||||
saveLineData(lineData); // Speichern der neuen Koordinaten nach dem Verschieben
|
||||
});
|
||||
};
|
||||
|
||||
export const removePOI = (marker, lineData, currentZoom, currentCenter) => {
|
||||
// Save zoom and center to localStorage
|
||||
//localStorage.setItem("mapZoom", currentZoom);
|
||||
//localStorage.setItem("mapCenter", JSON.stringify(currentCenter));
|
||||
|
||||
// Find the index of the coordinate that matches the marker's position
|
||||
const index = lineData.coordinates.findIndex((coord) => L.latLng(coord[0], coord[1]).equals(marker.getLatLng()));
|
||||
|
||||
if (index !== -1) {
|
||||
// Remove the coordinate from the line data
|
||||
lineData.coordinates.splice(index, 1);
|
||||
|
||||
// Redraw the polyline with the updated coordinates
|
||||
redrawPolyline(lineData);
|
||||
|
||||
// Remove the marker from the map
|
||||
marker.remove();
|
||||
|
||||
// Save the updated line data
|
||||
saveLineData(lineData);
|
||||
|
||||
// Refresh the browser
|
||||
window.location.reload();
|
||||
}
|
||||
};
|
||||
|
||||
export const handleEditPoi = (
|
||||
marker,
|
||||
userRights,
|
||||
setCurrentPoiData,
|
||||
setShowPoiUpdateModal,
|
||||
fetchPoiData,
|
||||
toast // Hier toast als Parameter erhalten
|
||||
) => {
|
||||
const editMode = localStorage.getItem("editMode") === "true";
|
||||
userRights = editMode ? userRights : undefined;
|
||||
//console.log("Selected Marker ID (idPoi):", marker.options.id);
|
||||
//console.log("Selected Marker Description:", marker.options.description);
|
||||
//console.log("User Rights:", userRights);
|
||||
|
||||
// Sicherstellen, dass userRights ein Array ist
|
||||
if (!Array.isArray(userRights)) {
|
||||
console.error("User Rights is not an array:", userRights);
|
||||
toast.error("Benutzerrechte sind ungültig.", {
|
||||
position: "top-center",
|
||||
autoClose: 5000,
|
||||
hideProgressBar: false,
|
||||
closeOnClick: true,
|
||||
pauseOnHover: true,
|
||||
draggable: true,
|
||||
progress: undefined,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("User Rights includes 56:", userRights.includes(56));
|
||||
|
||||
// Prüfung, ob der Benutzer die notwendigen Rechte hat
|
||||
if (!userRights.includes(56)) {
|
||||
toast.error("Benutzer hat keine Berechtigung zum Bearbeiten.", {
|
||||
position: "top-center",
|
||||
autoClose: 5000,
|
||||
hideProgressBar: false,
|
||||
closeOnClick: true,
|
||||
pauseOnHover: true,
|
||||
draggable: true,
|
||||
progress: undefined,
|
||||
});
|
||||
console.log("Benutzer hat keine Berechtigung zum Bearbeiten.");
|
||||
return; // Beendet die Funktion frühzeitig, wenn keine Berechtigung vorliegt
|
||||
}
|
||||
|
||||
setCurrentPoiData({
|
||||
idPoi: marker.options.id,
|
||||
name: marker.options.name,
|
||||
description: marker.options.description,
|
||||
idLD: marker.options.idLD,
|
||||
});
|
||||
|
||||
fetchPoiData(marker.options.id);
|
||||
|
||||
setShowPoiUpdateModal(true);
|
||||
};
|
||||
//-------------------------------------------------------------------
|
||||
131
utils/setupPOIs.js
Normal file
131
utils/setupPOIs.js
Normal file
@@ -0,0 +1,131 @@
|
||||
// utils/setupPOIs.js
|
||||
import { findClosestPoints } from "./geometryUtils";
|
||||
import handlePoiSelect from "./handlePoiSelect";
|
||||
import { updateLocationInDatabase } from "../services/apiService";
|
||||
import { handleEditPoi, insertNewPOI, removePOI } from "./poiUtils";
|
||||
import { parsePoint } from "./geometryUtils";
|
||||
import circleIcon from "../components/gisPolylines/icons/CircleIcon";
|
||||
import startIcon from "../components/gisPolylines/icons/StartIcon";
|
||||
import endIcon from "../components/gisPolylines/icons/EndIcon";
|
||||
import { redrawPolyline } from "./mapUtils";
|
||||
import { openInNewTab } from "../utils/openInNewTab";
|
||||
import { disablePolylineEvents, enablePolylineEvents } from "./setupPolylines"; // Importiere die Funktionen
|
||||
|
||||
export const setupPOIs = async (
|
||||
map,
|
||||
locations,
|
||||
poiData,
|
||||
poiTypMap,
|
||||
userRights,
|
||||
poiLayerRef,
|
||||
setSelectedPoi,
|
||||
setLocationDeviceData,
|
||||
setDeviceName,
|
||||
setCurrentPoi,
|
||||
poiLayerVisible,
|
||||
fetchPoiData,
|
||||
toast,
|
||||
setShowPoiUpdateModal,
|
||||
setCurrentPoiData,
|
||||
deviceName
|
||||
) => {
|
||||
const editMode = localStorage.getItem("editMode") === "true"; // Prüfen, ob der Bearbeitungsmodus aktiv ist
|
||||
userRights = editMode ? userRights : undefined; // Nur Berechtigungen anwenden, wenn editMode true ist
|
||||
|
||||
if (map && poiLayerRef.current) {
|
||||
map.removeLayer(poiLayerRef.current);
|
||||
poiLayerRef.current = new L.LayerGroup().addTo(map);
|
||||
|
||||
for (const location of locations) {
|
||||
try {
|
||||
const { latitude, longitude } = parsePoint(location.position);
|
||||
const poiTypName = poiTypMap.get(location.idPoiTyp) || "Unbekannt";
|
||||
const canDrag = userRights ? userRights.includes(56) : false;
|
||||
const matchingIcon = poiData.find((poi) => poi.idPoi === location.idPoi);
|
||||
const iconUrl = matchingIcon ? `/img/icons/pois/${matchingIcon.path}` : "/img/icons/pois/default-icon.png";
|
||||
|
||||
const marker = L.marker([latitude, longitude], {
|
||||
icon: L.icon({
|
||||
iconUrl: iconUrl,
|
||||
iconSize: [25, 41],
|
||||
iconAnchor: [12, 41],
|
||||
popupAnchor: [1, -34],
|
||||
}),
|
||||
draggable: canDrag,
|
||||
id: location.idPoi,
|
||||
name: location.name,
|
||||
description: location.description,
|
||||
idLD: location.idLD,
|
||||
link: location.link,
|
||||
});
|
||||
|
||||
// Nur das Kontextmenü "POI Bearbeiten" hinzufügen, wenn editMode true ist
|
||||
if (editMode) {
|
||||
marker.bindContextMenu({
|
||||
contextmenu: true,
|
||||
contextmenuWidth: 140,
|
||||
contextmenuItems: [
|
||||
{
|
||||
text: "POI Bearbeiten",
|
||||
icon: "/img/poi-edit.png",
|
||||
callback: () => handleEditPoi(marker, userRights, setCurrentPoiData, setShowPoiUpdateModal, fetchPoiData, toast),
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
marker.bindPopup(`
|
||||
<div>
|
||||
<b class="text-xl text-black-700">${location.description || "Unbekannt"}</b><br>
|
||||
${deviceName || "unbekannt"} <br>
|
||||
${poiTypName}<br>
|
||||
</div>
|
||||
`);
|
||||
|
||||
marker.on("mouseover", function () {
|
||||
console.log("Device Name:", marker); // Debugging
|
||||
handlePoiSelect(
|
||||
{
|
||||
id: location.idPoi,
|
||||
deviceId: location.idLD,
|
||||
idPoiTyp: location.idPoiTyp,
|
||||
typ: poiTypName,
|
||||
description: location.description,
|
||||
idLD: location.idLD,
|
||||
},
|
||||
setSelectedPoi,
|
||||
setLocationDeviceData,
|
||||
setDeviceName, // Stelle sicher, dass dies korrekt funktioniert
|
||||
poiLayerRef,
|
||||
poiTypMap
|
||||
);
|
||||
|
||||
localStorage.setItem("lastElementType", "marker");
|
||||
localStorage.setItem("markerLink", this.options.link);
|
||||
});
|
||||
|
||||
marker.on("mouseout", function () {
|
||||
this.closePopup();
|
||||
});
|
||||
|
||||
marker.on("dragend", (e) => {
|
||||
console.log("Marker wurde verschoben in setupPOIs");
|
||||
if (canDrag) {
|
||||
const newLat = e.target.getLatLng().lat;
|
||||
const newLng = e.target.getLatLng().lng;
|
||||
const markerId = e.target.options.id;
|
||||
updateLocationInDatabase(markerId, newLat, newLng).then(() => {});
|
||||
} else {
|
||||
console.error("Drag operation not allowed");
|
||||
}
|
||||
});
|
||||
|
||||
if (poiLayerVisible) {
|
||||
marker.addTo(poiLayerRef.current);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error processing a location:", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
341
utils/setupPolylines-back.js
Normal file
341
utils/setupPolylines-back.js
Normal file
@@ -0,0 +1,341 @@
|
||||
// utils/setupPolylines.js
|
||||
import { findClosestPoints } from "./geometryUtils";
|
||||
import handlePoiSelect from "./handlePoiSelect";
|
||||
import { updateLocationInDatabase } from "../services/apiService";
|
||||
import { handleEditPoi, insertNewPOI, removePOI } from "./poiUtils";
|
||||
import { parsePoint } from "./geometryUtils";
|
||||
import circleIcon from "../components/gisPolylines/icons/CircleIcon";
|
||||
import startIcon from "../components/gisPolylines/icons/StartIcon";
|
||||
import endIcon from "../components/gisPolylines/icons/EndIcon";
|
||||
import { redrawPolyline } from "./mapUtils";
|
||||
import { openInNewTab } from "./openInNewTab";
|
||||
import { toast } from "react-toastify";
|
||||
import { polylineLayerVisibleState } from "../store/atoms/polylineLayerVisibleState";
|
||||
import { useRecoilValue } from "recoil";
|
||||
|
||||
// Funktion zum Deaktivieren der Polyline-Ereignisse
|
||||
export function disablePolylineEvents(polylines) {
|
||||
polylines.forEach((polyline) => {
|
||||
polyline.off("mouseover");
|
||||
polyline.off("mouseout");
|
||||
});
|
||||
}
|
||||
|
||||
// Funktion zum Aktivieren der Polyline-Ereignisse
|
||||
export function enablePolylineEvents(polylines, lineColors) {
|
||||
// Überprüfe, ob polylines definiert ist und ob es Elemente enthält
|
||||
if (!polylines || polylines.length === 0) {
|
||||
//console.warn("Keine Polylinien vorhanden oder polylines ist undefined.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Falls Polylinien vorhanden sind, wende die Events an
|
||||
polylines.forEach((polyline) => {
|
||||
polyline.on("mouseover", (e) => {
|
||||
//console.log("Mouseover on polyline", polyline.options);
|
||||
polyline.setStyle({ weight: 14 });
|
||||
const link = `${process.env.NEXT_PUBLIC_BASE_URL}cpl.aspx?id=${polyline.options.idLD}`;
|
||||
//localStorage.setItem("lastElementType", "polyline");
|
||||
//localStorage.setItem("polylineLink", link);
|
||||
});
|
||||
|
||||
polyline.on("mouseout", (e) => {
|
||||
//console.log("Mouseout from polyline", polyline.options);
|
||||
polyline.setStyle({ weight: 3 });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export const setupPolylines = (map, linePositions, lineColors, tooltipContents, setNewCoords, tempMarker, currentZoom, currentCenter, polylineVisible) => {
|
||||
if (localStorage.getItem("polylineVisible") === null) {
|
||||
localStorage.setItem("polylineVisible", "true"); // Standardwert setzen
|
||||
polylineVisible = true; // Wert in der Funktion initialisieren
|
||||
} else {
|
||||
polylineVisible = localStorage.getItem("polylineVisible") === "true";
|
||||
}
|
||||
|
||||
if (!polylineVisible) {
|
||||
// Entferne alle Polylinien, wenn sie ausgeblendet werden sollen
|
||||
if (window.polylines) {
|
||||
window.polylines.forEach((polyline) => {
|
||||
if (map.hasLayer(polyline)) {
|
||||
map.removeLayer(polyline);
|
||||
}
|
||||
});
|
||||
}
|
||||
return { markers: [], polylines: [] };
|
||||
}
|
||||
const markers = [];
|
||||
const polylines = [];
|
||||
const editMode = localStorage.getItem("editMode") === "true"; // Prüfen, ob der Bearbeitungsmodus aktiv ist
|
||||
|
||||
linePositions.forEach((lineData, lineIndex) => {
|
||||
const lineMarkers = [];
|
||||
|
||||
lineData.coordinates.forEach((coord, index) => {
|
||||
let icon = circleIcon;
|
||||
if (index === 0) {
|
||||
icon = startIcon;
|
||||
} else if (index === lineData.coordinates.length - 1) {
|
||||
icon = endIcon;
|
||||
}
|
||||
|
||||
// Nur Marker mit circleIcon ausblenden, wenn Bearbeitungsmodus deaktiviert ist
|
||||
if (icon !== circleIcon || editMode) {
|
||||
const marker = L.marker(coord, {
|
||||
icon: icon,
|
||||
draggable: editMode, // Nur verschiebbar, wenn Bearbeitungsmodus aktiv ist
|
||||
contextmenu: true,
|
||||
contextmenuInheritItems: false,
|
||||
contextmenuItems: [],
|
||||
}).addTo(map);
|
||||
|
||||
marker.on("dragend", () => {
|
||||
console.log("Marker wurde verschoben in setupPolylines.js");
|
||||
if (editMode) {
|
||||
const newCoords = marker.getLatLng();
|
||||
setNewCoords(newCoords);
|
||||
const newCoordinates = [...lineData.coordinates];
|
||||
newCoordinates[index] = [newCoords.lat, newCoords.lng];
|
||||
|
||||
const updatedPolyline = L.polyline(newCoordinates, {
|
||||
color: lineColors[`${lineData.idLD}-${lineData.idModul}`] || "#000000",
|
||||
}).addTo(map);
|
||||
|
||||
updatedPolyline.bindTooltip(tooltipContents[`${lineData.idLD}-${lineData.idModul}`] || "Standard-Tooltip-Inhalt", {
|
||||
permanent: false,
|
||||
direction: "auto",
|
||||
});
|
||||
|
||||
updatedPolyline.on("mouseover", () => {
|
||||
updatedPolyline.setStyle({ weight: 20 });
|
||||
updatedPolyline.bringToFront();
|
||||
});
|
||||
|
||||
updatedPolyline.on("mouseout", () => {
|
||||
updatedPolyline.setStyle({ weight: 3 });
|
||||
});
|
||||
|
||||
polylines[lineIndex].remove();
|
||||
polylines[lineIndex] = updatedPolyline;
|
||||
lineData.coordinates = newCoordinates;
|
||||
|
||||
const requestData = {
|
||||
idModul: lineData.idModul,
|
||||
idLD: lineData.idLD,
|
||||
newCoordinates,
|
||||
};
|
||||
|
||||
fetch("/api/talas_v5_DB/gisLines/updateLineCoordinates", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(requestData),
|
||||
})
|
||||
.then((response) => {
|
||||
if (!response.ok) {
|
||||
return response.json().then((data) => {
|
||||
throw new Error(data.error || "Unbekannter Fehler");
|
||||
});
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then((data) => {
|
||||
console.log("Koordinaten erfolgreich aktualisiert:", data);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Fehler beim Aktualisieren der Koordinaten:", error.message);
|
||||
});
|
||||
} else {
|
||||
toast.error("Benutzer hat keine Berechtigung zum Bearbeiten.", {
|
||||
position: "top-center",
|
||||
autoClose: 5000,
|
||||
hideProgressBar: false,
|
||||
closeOnClick: true,
|
||||
pauseOnHover: true,
|
||||
draggable: true,
|
||||
progress: undefined,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
marker.on("mouseover", function () {
|
||||
this.bindContextMenu({
|
||||
contextmenuItems: [
|
||||
{
|
||||
text: "Stützpunkt entfernen",
|
||||
icon: "/img/icons/gisLines/remove-support-point.svg",
|
||||
callback: () => {
|
||||
if (editMode) {
|
||||
const newCoords = marker.getLatLng();
|
||||
const newCoordinates = [...lineData.coordinates];
|
||||
newCoordinates[index] = [newCoords.lat, newCoords.lng];
|
||||
|
||||
removePOI(marker, lineData, currentZoom, currentCenter);
|
||||
polylines[lineIndex].remove();
|
||||
lineData.coordinates = newCoordinates;
|
||||
} else {
|
||||
toast.error("Benutzer hat keine Berechtigung zum Bearbeiten.", {
|
||||
position: "top-center",
|
||||
autoClose: 5000,
|
||||
hideProgressBar: false,
|
||||
closeOnClick: true,
|
||||
pauseOnHover: true,
|
||||
draggable: true,
|
||||
progress: undefined,
|
||||
});
|
||||
}
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
marker.on("mouseout", function () {
|
||||
this.unbindContextMenu();
|
||||
});
|
||||
|
||||
lineMarkers.push(marker);
|
||||
}
|
||||
});
|
||||
|
||||
const polyline = L.polyline(lineData.coordinates, {
|
||||
color: lineColors[`${lineData.idLD}-${lineData.idModul}`] || "#000000",
|
||||
weight: 3,
|
||||
contextmenu: true,
|
||||
contextmenuInheritItems: false, // Standard-Kontextmenü deaktivieren
|
||||
contextmenuItems: [],
|
||||
}).addTo(map);
|
||||
|
||||
// Füge "Stützpunkt hinzufügen" nur hinzu, wenn editMode aktiv ist
|
||||
if (editMode) {
|
||||
polyline.options.contextmenuItems.push(
|
||||
{
|
||||
text: "Station öffnen (Tab)",
|
||||
icon: "/img/screen_new.png",
|
||||
callback: (e) => {
|
||||
const link = `${process.env.NEXT_PUBLIC_BASE_URL}cpl.aspx?ver=35&kue=24&id=${lineData.idLD}`;
|
||||
window.open(link, "_blank");
|
||||
},
|
||||
},
|
||||
{ separator: true },
|
||||
|
||||
{
|
||||
text: "Koordinaten anzeigen",
|
||||
icon: "/img/not_listed_location.png",
|
||||
callback: (e) => {
|
||||
alert("Breitengrad: " + e.latlng.lat.toFixed(5) + "\nLängengrad: " + e.latlng.lng.toFixed(5));
|
||||
},
|
||||
},
|
||||
{ separator: true },
|
||||
{
|
||||
text: "Reinzoomen",
|
||||
icon: "/img/zoom_in.png",
|
||||
callback: (e) => map.zoomIn(),
|
||||
},
|
||||
{
|
||||
text: "Rauszoomen",
|
||||
icon: "/img/zoom_out.png",
|
||||
callback: (e) => map.zoomOut(),
|
||||
},
|
||||
{
|
||||
text: "Hier zentrieren",
|
||||
icon: "/img/center_focus.png",
|
||||
callback: (e) => map.panTo(e.latlng),
|
||||
},
|
||||
{ separator: true },
|
||||
{
|
||||
text: "POI hinzufügen",
|
||||
icon: "/img/add_station.png",
|
||||
callback: (e) => {
|
||||
// Hier kannst du die Logik für das Hinzufügen eines POIs implementieren
|
||||
alert("POI hinzufügen an: " + e.latlng);
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Stützpunkt hinzufügen",
|
||||
icon: "/img/icons/gisLines/add-support-point.svg",
|
||||
callback: (e) => {
|
||||
if (tempMarker) {
|
||||
tempMarker.remove();
|
||||
}
|
||||
const newPoint = e.latlng;
|
||||
const closestPoints = findClosestPoints(lineData.coordinates, newPoint, map);
|
||||
insertNewPOI(closestPoints, newPoint, lineData, map);
|
||||
redrawPolyline(lineData, lineColors, tooltipContents, map);
|
||||
window.location.reload();
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// Hier wird der Tooltip hinzugefügt
|
||||
polyline.bindTooltip(tooltipContents[`${lineData.idLD}-${lineData.idModul}`] || "Standard-Tooltip-Inhalt", {
|
||||
permanent: false,
|
||||
direction: "auto",
|
||||
});
|
||||
|
||||
polyline.on("mouseover", (e) => {
|
||||
const startTime = Date.now(); // Startzeit erfassen
|
||||
localStorage.setItem("contextMenuStartTime", startTime); // Speichern in localStorage
|
||||
|
||||
// Starte einen Intervall-Timer, um die Differenz zu berechnen
|
||||
const countdownInterval = setInterval(() => {
|
||||
const currentTime = Date.now();
|
||||
const elapsedTime = (currentTime - startTime) / 1000; // Differenz in Sekunden
|
||||
|
||||
// Speichern der abgelaufenen Zeit in localStorage
|
||||
localStorage.setItem("contextMenuCountdown", elapsedTime);
|
||||
|
||||
// Wenn die Zeit 17 Sekunden erreicht, schließe das Menü
|
||||
if (elapsedTime >= 17) {
|
||||
clearInterval(countdownInterval);
|
||||
const contextMenu = map.contextmenu; // Zugriff auf das Kontextmenü
|
||||
contextMenu.hide(); // Kontextmenü schließen
|
||||
}
|
||||
}, 1000); // Jede Sekunde
|
||||
//console.log("Mouseover on polyline", lineData);
|
||||
polyline.setStyle({ weight: 14 });
|
||||
const link = `${process.env.NEXT_PUBLIC_BASE_URL}cpl.aspx?ver=35&kue=24&id=${lineData.idLD}`;
|
||||
console.log("Link der Linie:", link);
|
||||
//localStorage.setItem("lastElementType", "polyline");
|
||||
//localStorage.setItem("polylineLink", link);
|
||||
});
|
||||
|
||||
polyline.on("mouseout", (e) => {
|
||||
// console.log("Mouseout from polyline", lineData);
|
||||
polyline.setStyle({ weight: 3 });
|
||||
// Setze den Countdown auf 0, wenn mouseout ausgelöst wird
|
||||
localStorage.setItem("contextMenuCountdown", 0);
|
||||
});
|
||||
// Speichere den Link bei einem Rechtsklick (Kontextmenü)
|
||||
/*
|
||||
polyline.on("contextmenu", (e) => {
|
||||
const link = `${process.env.NEXT_PUBLIC_BASE_URL}cpl.aspx?ver=35&kue=24&id=${lineData.idLD}`;
|
||||
console.log("Link der Linie (via Rechtsklick):", link);
|
||||
localStorage.setItem("lastElementType", "polyline");
|
||||
localStorage.setItem("polylineLink", link);
|
||||
});
|
||||
*/
|
||||
// Starte den Timer zum Schließen des Kontextmenüs nach 15 Sekunden
|
||||
polyline.on("contextmenu", function (e) {
|
||||
const contextMenu = this._map.contextmenu; // Zugriff auf das Kontextmenü
|
||||
const closeMenu = () => contextMenu.hide(); // Funktion zum Schließen des Menüs
|
||||
|
||||
const countdown = parseInt(localStorage.getItem("contextMenuCountdown"), 30);
|
||||
if (countdown >= 28) {
|
||||
closeMenu();
|
||||
}
|
||||
});
|
||||
|
||||
polylines.push(polyline);
|
||||
markers.push(...lineMarkers);
|
||||
});
|
||||
|
||||
// Speichere Polylines und LineColors global für den Zugriff in anderen Funktionen
|
||||
window.polylines = polylines;
|
||||
window.lineColors = lineColors;
|
||||
|
||||
return { markers, polylines };
|
||||
};
|
||||
423
utils/setupPolylines.js
Normal file
423
utils/setupPolylines.js
Normal file
@@ -0,0 +1,423 @@
|
||||
// utils/setupPolylines.js
|
||||
import { findClosestPoints } from "./geometryUtils";
|
||||
import handlePoiSelect from "./handlePoiSelect";
|
||||
import { updateLocationInDatabase } from "../services/apiService";
|
||||
import { handleEditPoi, insertNewPOI, removePOI } from "./poiUtils";
|
||||
import { parsePoint } from "./geometryUtils";
|
||||
import circleIcon from "../components/gisPolylines/icons/CircleIcon";
|
||||
import startIcon from "../components/gisPolylines/icons/StartIcon";
|
||||
import endIcon from "../components/gisPolylines/icons/EndIcon";
|
||||
import { redrawPolyline } from "./mapUtils";
|
||||
import { openInNewTab } from "./openInNewTab";
|
||||
import { toast } from "react-toastify";
|
||||
import { polylineLayerVisibleState } from "../store/atoms/polylineLayerVisibleState";
|
||||
import { useRecoilValue } from "recoil";
|
||||
|
||||
// Funktion zum Deaktivieren der Polyline-Ereignisse
|
||||
export function disablePolylineEvents(polylines) {
|
||||
polylines.forEach((polyline) => {
|
||||
polyline.off("mouseover");
|
||||
polyline.off("mouseout");
|
||||
});
|
||||
}
|
||||
|
||||
// Funktion zum Aktivieren der Polyline-Ereignisse
|
||||
export function enablePolylineEvents(polylines, lineColors) {
|
||||
// Überprüfe, ob polylines definiert ist und ob es Elemente enthält
|
||||
if (!polylines || polylines.length === 0) {
|
||||
//console.warn("Keine Polylinien vorhanden oder polylines ist undefined.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Falls Polylinien vorhanden sind, wende die Events an
|
||||
polylines.forEach((polyline) => {
|
||||
polyline.on("mouseover", (e) => {
|
||||
//console.log("Mouseover on polyline", polyline.options);
|
||||
polyline.setStyle({ weight: 14 });
|
||||
const link = `${process.env.NEXT_PUBLIC_BASE_URL}cpl.aspx?id=${polyline.options.idLD}`;
|
||||
//localStorage.setItem("lastElementType", "polyline");
|
||||
//localStorage.setItem("polylineLink", link);
|
||||
});
|
||||
|
||||
polyline.on("mouseout", (e) => {
|
||||
//console.log("Mouseout from polyline", polyline.options);
|
||||
polyline.setStyle({ weight: 3 });
|
||||
});
|
||||
});
|
||||
}
|
||||
// Funktion zum Schließen des Kontextmenüs und Entfernen der Markierung
|
||||
function closePolylineSelectionAndContextMenu(map) {
|
||||
try {
|
||||
// Entferne alle markierten Polylinien
|
||||
if (window.selectedPolyline) {
|
||||
window.selectedPolyline.setStyle({ weight: 3 }); // Originalstil wiederherstellen
|
||||
window.selectedPolyline = null;
|
||||
}
|
||||
|
||||
// Überprüfe, ob map und map.contextmenu definiert sind
|
||||
if (map && map.contextmenu) {
|
||||
map.contextmenu.hide(); // Kontextmenü schließen
|
||||
} else {
|
||||
console.warn("Kontextmenü ist nicht verfügbar.");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Fehler beim Schließen des Kontextmenüs:", error);
|
||||
window.location.reload();
|
||||
}
|
||||
|
||||
// Countdown-Status zurücksetzen
|
||||
localStorage.removeItem("contextMenuCountdown");
|
||||
localStorage.removeItem("contextMenuExpired");
|
||||
}
|
||||
|
||||
// Überprüft regelmäßig den Status in localStorage
|
||||
function monitorContextMenu(map) {
|
||||
setInterval(() => {
|
||||
const isContextMenuExpired = localStorage.getItem("contextMenuExpired") === "true";
|
||||
if (isContextMenuExpired) {
|
||||
closePolylineSelectionAndContextMenu(map);
|
||||
localStorage.removeItem("contextMenuExpired"); // Flagge entfernen, um wiederverwendbar zu sein
|
||||
}
|
||||
}, 1000); // Alle 1 Sekunde überprüfen
|
||||
}
|
||||
|
||||
export const setupPolylines = (map, linePositions, lineColors, tooltipContents, setNewCoords, tempMarker, currentZoom, currentCenter, polylineVisible) => {
|
||||
if (localStorage.getItem("polylineVisible") === null) {
|
||||
localStorage.setItem("polylineVisible", "true"); // Standardwert setzen
|
||||
polylineVisible = true; // Wert in der Funktion initialisieren
|
||||
} else {
|
||||
polylineVisible = localStorage.getItem("polylineVisible") === "true";
|
||||
}
|
||||
|
||||
if (!polylineVisible) {
|
||||
// Entferne alle Polylinien, wenn sie ausgeblendet werden sollen
|
||||
if (window.polylines) {
|
||||
window.polylines.forEach((polyline) => {
|
||||
if (map.hasLayer(polyline)) {
|
||||
map.removeLayer(polyline);
|
||||
}
|
||||
});
|
||||
}
|
||||
return { markers: [], polylines: [] };
|
||||
}
|
||||
const markers = [];
|
||||
const polylines = [];
|
||||
const editMode = localStorage.getItem("editMode") === "true"; // Prüfen, ob der Bearbeitungsmodus aktiv ist
|
||||
|
||||
linePositions.forEach((lineData, lineIndex) => {
|
||||
const lineMarkers = [];
|
||||
|
||||
lineData.coordinates.forEach((coord, index) => {
|
||||
let icon = circleIcon;
|
||||
if (index === 0) {
|
||||
icon = startIcon;
|
||||
} else if (index === lineData.coordinates.length - 1) {
|
||||
icon = endIcon;
|
||||
}
|
||||
|
||||
// Nur Marker mit circleIcon ausblenden, wenn Bearbeitungsmodus deaktiviert ist
|
||||
if (icon !== circleIcon || editMode) {
|
||||
const marker = L.marker(coord, {
|
||||
icon: icon,
|
||||
draggable: editMode, // Nur verschiebbar, wenn Bearbeitungsmodus aktiv ist
|
||||
contextmenu: true,
|
||||
contextmenuInheritItems: false,
|
||||
contextmenuItems: [],
|
||||
}).addTo(map);
|
||||
|
||||
marker.on("dragend", () => {
|
||||
console.log("Marker wurde verschoben in setupPolylines.js");
|
||||
if (editMode) {
|
||||
const newCoords = marker.getLatLng();
|
||||
setNewCoords(newCoords);
|
||||
const newCoordinates = [...lineData.coordinates];
|
||||
newCoordinates[index] = [newCoords.lat, newCoords.lng];
|
||||
|
||||
const updatedPolyline = L.polyline(newCoordinates, {
|
||||
color: lineColors[`${lineData.idLD}-${lineData.idModul}`] || "#000000",
|
||||
}).addTo(map);
|
||||
|
||||
updatedPolyline.bindTooltip(tooltipContents[`${lineData.idLD}-${lineData.idModul}`] || "Standard-Tooltip-Inhalt", {
|
||||
permanent: false,
|
||||
direction: "auto",
|
||||
});
|
||||
|
||||
updatedPolyline.on("mouseover", () => {
|
||||
updatedPolyline.setStyle({ weight: 20 });
|
||||
updatedPolyline.bringToFront();
|
||||
});
|
||||
|
||||
updatedPolyline.on("mouseout", () => {
|
||||
updatedPolyline.setStyle({ weight: 3 });
|
||||
});
|
||||
|
||||
polylines[lineIndex].remove();
|
||||
polylines[lineIndex] = updatedPolyline;
|
||||
lineData.coordinates = newCoordinates;
|
||||
|
||||
const requestData = {
|
||||
idModul: lineData.idModul,
|
||||
idLD: lineData.idLD,
|
||||
newCoordinates,
|
||||
};
|
||||
|
||||
fetch("/api/talas_v5_DB/gisLines/updateLineCoordinates", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(requestData),
|
||||
})
|
||||
.then((response) => {
|
||||
if (!response.ok) {
|
||||
return response.json().then((data) => {
|
||||
throw new Error(data.error || "Unbekannter Fehler");
|
||||
});
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then((data) => {
|
||||
console.log("Koordinaten erfolgreich aktualisiert:", data);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Fehler beim Aktualisieren der Koordinaten:", error.message);
|
||||
});
|
||||
} else {
|
||||
toast.error("Benutzer hat keine Berechtigung zum Bearbeiten.", {
|
||||
position: "top-center",
|
||||
autoClose: 5000,
|
||||
hideProgressBar: false,
|
||||
closeOnClick: true,
|
||||
pauseOnHover: true,
|
||||
draggable: true,
|
||||
progress: undefined,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
marker.on("mouseover", function () {
|
||||
this.bindContextMenu({
|
||||
contextmenuItems: [
|
||||
{
|
||||
text: "Stützpunkt entfernen",
|
||||
icon: "/img/icons/gisLines/remove-support-point.svg",
|
||||
callback: () => {
|
||||
if (editMode) {
|
||||
const newCoords = marker.getLatLng();
|
||||
const newCoordinates = [...lineData.coordinates];
|
||||
newCoordinates[index] = [newCoords.lat, newCoords.lng];
|
||||
|
||||
removePOI(marker, lineData, currentZoom, currentCenter);
|
||||
polylines[lineIndex].remove();
|
||||
lineData.coordinates = newCoordinates;
|
||||
} else {
|
||||
toast.error("Benutzer hat keine Berechtigung zum Bearbeiten.", {
|
||||
position: "top-center",
|
||||
autoClose: 5000,
|
||||
hideProgressBar: false,
|
||||
closeOnClick: true,
|
||||
pauseOnHover: true,
|
||||
draggable: true,
|
||||
progress: undefined,
|
||||
});
|
||||
}
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
marker.on("mouseout", function () {
|
||||
this.unbindContextMenu();
|
||||
});
|
||||
|
||||
lineMarkers.push(marker);
|
||||
}
|
||||
});
|
||||
|
||||
const polyline = L.polyline(lineData.coordinates, {
|
||||
color: lineColors[`${lineData.idLD}-${lineData.idModul}`] || "#000000",
|
||||
weight: 3,
|
||||
contextmenu: true,
|
||||
contextmenuInheritItems: false, // Standard-Kontextmenü deaktivieren
|
||||
contextmenuItems: [],
|
||||
}).addTo(map);
|
||||
|
||||
// Füge "Stützpunkt hinzufügen" nur hinzu, wenn editMode aktiv ist
|
||||
if (editMode) {
|
||||
polyline.options.contextmenuItems.push(
|
||||
{
|
||||
text: "Station öffnen (Tab)",
|
||||
icon: "/img/screen_new.png",
|
||||
callback: (e) => {
|
||||
const link = `${process.env.NEXT_PUBLIC_BASE_URL}cpl.aspx?ver=35&kue=24&id=${lineData.idLD}`;
|
||||
window.open(link, "_blank");
|
||||
},
|
||||
},
|
||||
{ separator: true },
|
||||
|
||||
{
|
||||
text: "Koordinaten anzeigen",
|
||||
icon: "/img/not_listed_location.png",
|
||||
callback: (e) => {
|
||||
alert("Breitengrad: " + e.latlng.lat.toFixed(5) + "\nLängengrad: " + e.latlng.lng.toFixed(5));
|
||||
},
|
||||
},
|
||||
{ separator: true },
|
||||
{
|
||||
text: "Reinzoomen",
|
||||
icon: "/img/zoom_in.png",
|
||||
callback: (e) => map.zoomIn(),
|
||||
},
|
||||
{
|
||||
text: "Rauszoomen",
|
||||
icon: "/img/zoom_out.png",
|
||||
callback: (e) => map.zoomOut(),
|
||||
},
|
||||
{
|
||||
text: "Hier zentrieren",
|
||||
icon: "/img/center_focus.png",
|
||||
callback: (e) => map.panTo(e.latlng),
|
||||
},
|
||||
{ separator: true },
|
||||
{
|
||||
text: "POI hinzufügen",
|
||||
icon: "/img/add_station.png",
|
||||
callback: (e) => {
|
||||
// Hier kannst du die Logik für das Hinzufügen eines POIs implementieren
|
||||
alert("POI hinzufügen an: " + e.latlng);
|
||||
},
|
||||
},
|
||||
{
|
||||
text: "Stützpunkt hinzufügen",
|
||||
icon: "/img/icons/gisLines/add-support-point.svg",
|
||||
callback: (e) => {
|
||||
if (tempMarker) {
|
||||
tempMarker.remove();
|
||||
}
|
||||
const newPoint = e.latlng;
|
||||
const closestPoints = findClosestPoints(lineData.coordinates, newPoint, map);
|
||||
insertNewPOI(closestPoints, newPoint, lineData, map);
|
||||
redrawPolyline(lineData, lineColors, tooltipContents, map);
|
||||
window.location.reload();
|
||||
},
|
||||
}
|
||||
);
|
||||
} else {
|
||||
polyline.options.contextmenuItems.push(
|
||||
{
|
||||
text: "Station öffnen (Tab)",
|
||||
icon: "/img/screen_new.png",
|
||||
callback: (e) => {
|
||||
const link = `${process.env.NEXT_PUBLIC_BASE_URL}cpl.aspx?ver=35&kue=24&id=${lineData.idLD}`;
|
||||
window.open(link, "_blank");
|
||||
},
|
||||
},
|
||||
{ separator: true },
|
||||
|
||||
{
|
||||
text: "Koordinaten anzeigen",
|
||||
icon: "/img/not_listed_location.png",
|
||||
callback: (e) => {
|
||||
alert("Breitengrad: " + e.latlng.lat.toFixed(5) + "\nLängengrad: " + e.latlng.lng.toFixed(5));
|
||||
},
|
||||
},
|
||||
{ separator: true },
|
||||
{
|
||||
text: "Reinzoomen",
|
||||
icon: "/img/zoom_in.png",
|
||||
callback: (e) => map.zoomIn(),
|
||||
},
|
||||
{
|
||||
text: "Rauszoomen",
|
||||
icon: "/img/zoom_out.png",
|
||||
callback: (e) => map.zoomOut(),
|
||||
},
|
||||
|
||||
{
|
||||
text: "Hier zentrieren",
|
||||
icon: "/img/center_focus.png",
|
||||
callback: (e) => map.panTo(e.latlng),
|
||||
},
|
||||
{ separator: true },
|
||||
{
|
||||
text: "POI hinzufügen",
|
||||
icon: "/img/add_station.png",
|
||||
callback: (e) => {
|
||||
// Hier kannst du die Logik für das Hinzufügen eines POIs implementieren
|
||||
alert("POI hinzufügen an: " + e.latlng);
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// Hier wird der Tooltip hinzugefügt
|
||||
polyline.bindTooltip(tooltipContents[`${lineData.idLD}-${lineData.idModul}`] || "Standard-Tooltip-Inhalt", {
|
||||
permanent: false,
|
||||
direction: "auto",
|
||||
});
|
||||
|
||||
polyline.on("mouseover", (e) => {
|
||||
const startTime = Date.now(); // Startzeit erfassen
|
||||
localStorage.setItem("contextMenuStartTime", startTime); // Speichern in localStorage
|
||||
|
||||
// Starte einen Intervall-Timer, um die Differenz zu berechnen
|
||||
/* const countdownInterval = setInterval(() => {
|
||||
const currentTime = Date.now();
|
||||
const elapsedTime = (currentTime - startTime) / 1000; // Differenz in Sekunden
|
||||
|
||||
// Speichern der abgelaufenen Zeit in localStorage
|
||||
localStorage.setItem("contextMenuCountdown", elapsedTime);
|
||||
|
||||
// Wenn die Zeit 17 Sekunden erreicht, schließe das Menü
|
||||
if (elapsedTime >= 17) {
|
||||
clearInterval(countdownInterval);
|
||||
const contextMenu = map.contextmenu; // Zugriff auf das Kontextmenü
|
||||
contextMenu.hide(); // Kontextmenü schließen
|
||||
}
|
||||
}, 1000); */
|
||||
// Jede Sekunde
|
||||
//console.log("Mouseover on polyline", lineData);
|
||||
polyline.setStyle({ weight: 14 });
|
||||
const link = `${process.env.NEXT_PUBLIC_BASE_URL}cpl.aspx?ver=35&kue=24&id=${lineData.idLD}`;
|
||||
console.log("Link der Linie:", link);
|
||||
//localStorage.setItem("lastElementType", "polyline");
|
||||
//localStorage.setItem("polylineLink", link);
|
||||
});
|
||||
|
||||
polyline.on("mouseout", (e) => {
|
||||
// console.log("Mouseout from polyline", lineData);
|
||||
polyline.setStyle({ weight: 3 });
|
||||
// Setze den Countdown auf 0, wenn mouseout ausgelöst wird
|
||||
localStorage.setItem("contextMenuCountdown", 0);
|
||||
});
|
||||
// Speichere den Link bei einem Rechtsklick (Kontextmenü)
|
||||
/*
|
||||
polyline.on("contextmenu", (e) => {
|
||||
const link = `${process.env.NEXT_PUBLIC_BASE_URL}cpl.aspx?ver=35&kue=24&id=${lineData.idLD}`;
|
||||
console.log("Link der Linie (via Rechtsklick):", link);
|
||||
localStorage.setItem("lastElementType", "polyline");
|
||||
localStorage.setItem("polylineLink", link);
|
||||
});
|
||||
*/
|
||||
// Starte den Timer zum Schließen des Kontextmenüs nach 15 Sekunden
|
||||
polyline.on("contextmenu", function (e) {
|
||||
const contextMenu = this._map.contextmenu; // Zugriff auf das Kontextmenü
|
||||
const closeMenu = () => contextMenu.hide(); // Funktion zum Schließen des Menüs
|
||||
|
||||
const countdown = parseInt(localStorage.getItem("contextMenuCountdown"), 30);
|
||||
if (countdown >= 28) {
|
||||
closeMenu();
|
||||
}
|
||||
});
|
||||
|
||||
polylines.push(polyline);
|
||||
markers.push(...lineMarkers);
|
||||
});
|
||||
|
||||
// Speichere Polylines und LineColors global für den Zugriff in anderen Funktionen
|
||||
window.polylines = polylines;
|
||||
window.lineColors = lineColors;
|
||||
monitorContextMenu(map);
|
||||
return { markers, polylines };
|
||||
};
|
||||
@@ -14,9 +14,14 @@ export const zoomIn = (e, map) => {
|
||||
console.error("map is not defined in zoomIn");
|
||||
return;
|
||||
}
|
||||
map.flyTo(e.latlng, 12);
|
||||
localStorage.setItem("mapZoom", map.getZoom());
|
||||
localStorage.setItem("mapCenter", JSON.stringify(map.getCenter()));
|
||||
|
||||
const currentZoom = map.getZoom();
|
||||
|
||||
if (currentZoom < 14) {
|
||||
map.flyTo(e.latlng, 14);
|
||||
localStorage.setItem("mapZoom", 16);
|
||||
localStorage.setItem("mapCenter", JSON.stringify(map.getCenter()));
|
||||
}
|
||||
};
|
||||
|
||||
export const zoomOut = (map) => {
|
||||
@@ -24,14 +29,18 @@ export const zoomOut = (map) => {
|
||||
console.error("map is not defined in zoomOut");
|
||||
return;
|
||||
}
|
||||
const x = 51.41321407879154;
|
||||
const y = 7.739617925303934;
|
||||
const zoom = 7;
|
||||
console.log("map");
|
||||
console.log(map);
|
||||
map.flyTo([x, y], zoom);
|
||||
localStorage.setItem("mapZoom", map.getZoom());
|
||||
localStorage.setItem("mapCenter", JSON.stringify(map.getCenter()));
|
||||
|
||||
const currentZoom = map.getZoom();
|
||||
|
||||
if (currentZoom > 7) {
|
||||
const x = 51.41321407879154;
|
||||
const y = 7.739617925303934;
|
||||
const zoom = 7;
|
||||
|
||||
map.flyTo([x, y], zoom);
|
||||
localStorage.setItem("mapZoom", zoom);
|
||||
localStorage.setItem("mapCenter", JSON.stringify(map.getCenter()));
|
||||
}
|
||||
};
|
||||
|
||||
export const centerHere = (e, map) => {
|
||||
|
||||
Reference in New Issue
Block a user