268 lines
8.0 KiB
TypeScript
268 lines
8.0 KiB
TypeScript
'use client';
|
|
|
|
import React, { useEffect, useRef, useState, useCallback, createElement } from 'react';
|
|
import * as maplibregl from 'maplibre-gl';
|
|
import 'maplibre-gl/dist/maplibre-gl.css';
|
|
import styles from '@/css/MapView.module.css';
|
|
|
|
export interface PlaceMarker {
|
|
id: number;
|
|
lat: number;
|
|
lng: number;
|
|
title?: string;
|
|
description?: string;
|
|
}
|
|
|
|
export interface MapViewProps {
|
|
initialCenter?: [number, number]; // [lng, lat]
|
|
initialZoom?: number;
|
|
markers?: PlaceMarker[];
|
|
onMarkerClick?: (marker: PlaceMarker) => void;
|
|
// Default vector tile source or tile pattern
|
|
tileUrlTemplate?: string;
|
|
}
|
|
|
|
// MapTile calculations for Bounding Box precaching (Slippy Map Tile Names)
|
|
function lng2tile(lng: number, zoom: number): number {
|
|
return Math.floor(((lng + 180) / 360) * Math.pow(2, zoom));
|
|
}
|
|
|
|
function lat2tile(lat: number, zoom: number): number {
|
|
return Math.floor(
|
|
((1 - Math.log(Math.tan((lat * Math.PI) / 180) + 1 / Math.cos((lat * Math.PI) / 180)) / Math.PI) / 2) *
|
|
Math.pow(2, zoom)
|
|
);
|
|
}
|
|
|
|
const TILE_CACHE_NAME = 'excalibur-offline-map-tiles-v1';
|
|
const DEFAULT_TILE_URL = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png';
|
|
|
|
export default function MapView({
|
|
initialCenter = [9.282050, 49.090165],
|
|
initialZoom = 15,
|
|
markers = [],
|
|
onMarkerClick,
|
|
tileUrlTemplate = DEFAULT_TILE_URL,
|
|
}: MapViewProps) {
|
|
const mapContainerRef = useRef<HTMLDivElement>(null);
|
|
const mapRef = useRef<maplibregl.Map | null>(null);
|
|
const activeMarkersRef = useRef<Map<number, maplibregl.Marker>>(new Map());
|
|
const [ mapReady, setMapReady ] = useState(false);
|
|
|
|
const [isCaching, setIsCaching] = useState(false);
|
|
const [cacheProgress, setCacheProgress] = useState<{ loaded: number; total: number } | null>(null);
|
|
|
|
useEffect(() => {
|
|
if (!mapContainerRef.current) return;
|
|
if (mapRef.current) return;
|
|
|
|
const mapStyle: maplibregl.StyleSpecification = {
|
|
version: 8,
|
|
sources: {
|
|
'osm-tiles': {
|
|
type: 'raster',
|
|
tiles: [tileUrlTemplate],
|
|
tileSize: 256,
|
|
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
|
|
},
|
|
},
|
|
layers: [
|
|
{
|
|
id: 'osm-tiles-layer',
|
|
type: 'raster',
|
|
source: 'osm-tiles',
|
|
minzoom: 0,
|
|
maxzoom: 19,
|
|
}
|
|
],
|
|
};
|
|
|
|
const map = new maplibregl.Map({
|
|
container: mapContainerRef.current,
|
|
style: mapStyle,
|
|
center: initialCenter,
|
|
zoom: initialZoom,
|
|
});
|
|
|
|
map.addControl(new maplibregl.NavigationControl({ visualizePitch: true }), 'bottom-right');
|
|
|
|
const el = document.createElement("img");
|
|
el.src = "/icons/person.svg";
|
|
el.alt = "You";
|
|
el.width = 42;
|
|
el.className = styles["sword"];
|
|
|
|
const geolocate = new maplibregl.GeolocateControl({
|
|
positionOptions: {
|
|
enableHighAccuracy: true,
|
|
},
|
|
trackUserLocation: true,
|
|
showUserLocation: true,
|
|
showAccuracyCircle: false,
|
|
});
|
|
geolocate._dotElement = el;
|
|
map.addControl(geolocate, 'bottom-right');
|
|
|
|
map.addControl(new maplibregl.ScaleControl({ unit: 'metric' }), 'bottom-left');
|
|
|
|
map.on('load', async () => {
|
|
setMapReady(true);
|
|
/*navigator.geolocation.getCurrentPosition((pos) => {
|
|
map.setCenter([pos.coords.longitude, pos.coords.latitude]);
|
|
geolocate.trigger();
|
|
}, () => {
|
|
geolocate.trigger();
|
|
});*/
|
|
}); // TODO: ACTIVATE AFTER TESTING
|
|
|
|
mapRef.current = map;
|
|
|
|
return () => {
|
|
map.remove();
|
|
mapRef.current = null;
|
|
setMapReady(false);
|
|
};
|
|
}, [/*initialCenter, initialZoom, tileUrlTemplate Create your own listeners*/]);
|
|
|
|
useEffect(() => {
|
|
const map = mapRef.current;
|
|
if (!map || !mapReady) return;
|
|
|
|
const currentMarkers = activeMarkersRef.current;
|
|
const incomingMarkerIds = new Set(markers.map((m) => m.id));
|
|
|
|
//console.log(incomingMarkerIds);
|
|
|
|
currentMarkers.forEach((markerInstance, id) => {
|
|
if (!incomingMarkerIds.has(id)) {
|
|
markerInstance.remove();
|
|
currentMarkers.delete(id);
|
|
}
|
|
});
|
|
|
|
markers.forEach((markerData) => {
|
|
if (!currentMarkers.has(markerData.id)) {
|
|
/*const popup = new maplibregl.Popup({ offset: 25, className: styles["marker"] }).setHTML(
|
|
`<strong>${markerData.title}</strong>${
|
|
markerData.description ? `<p style="margin:4px 0 0;font-size:12px;">${markerData.description}</p>` : ''
|
|
}`
|
|
);*/
|
|
|
|
const el = document.createElement("img");
|
|
el.src = "/icons/Schwert-gps.svg";
|
|
el.alt = "GPS Point";
|
|
el.width = 80;
|
|
el.className = styles["sword"];
|
|
|
|
const newMarker = new maplibregl.Marker({ element: el, anchor: "bottom" })
|
|
.setLngLat([markerData.lng, markerData.lat])
|
|
//.setPopup(popup)
|
|
.addTo(map);
|
|
|
|
newMarker.getElement().addEventListener('click', () => {
|
|
onMarkerClick?.(markerData);
|
|
});
|
|
|
|
currentMarkers.set(markerData.id, newMarker);
|
|
}
|
|
});
|
|
}, [mapReady, markers, onMarkerClick]);
|
|
|
|
const precacheCurrentRegion = useCallback(async () => {
|
|
const map = mapRef.current;
|
|
if (!map) return;
|
|
|
|
setIsCaching(true);
|
|
setCacheProgress({ loaded: 0, total: 0 });
|
|
|
|
const bounds = map.getBounds();
|
|
const currentZoom = Math.floor(map.getZoom());
|
|
|
|
// Precache current zoom level + 3 additional detailed zoom levels for hiking trails
|
|
const minZoom = Math.max(10, currentZoom);
|
|
const maxZoom = Math.min(17, currentZoom + 3);
|
|
|
|
const tileUrls: string[] = [];
|
|
|
|
for (let z = minZoom; z <= maxZoom; z++) {
|
|
const minX = lng2tile(bounds.getWest(), z);
|
|
const maxX = lng2tile(bounds.getEast(), z);
|
|
const minY = lat2tile(bounds.getNorth(), z);
|
|
const maxY = lat2tile(bounds.getSouth(), z);
|
|
|
|
for (let x = Math.min(minX, maxX); x <= Math.max(minX, maxX); x++) {
|
|
for (let y = Math.min(minY, maxY); y <= Math.max(minY, maxY); y++) {
|
|
const url = tileUrlTemplate
|
|
.replace('{z}', z.toString())
|
|
.replace('{x}', x.toString())
|
|
.replace('{y}', y.toString());
|
|
tileUrls.push(url);
|
|
}
|
|
}
|
|
}
|
|
|
|
setCacheProgress({ loaded: 0, total: tileUrls.length });
|
|
|
|
try {
|
|
const cache = await caches.open(TILE_CACHE_NAME);
|
|
let loaded = 0;
|
|
|
|
// Fetch tiles in batches to avoid network throttling
|
|
const BATCH_SIZE = 6;
|
|
for (let i = 0; i < tileUrls.length; i += BATCH_SIZE) {
|
|
const batch = tileUrls.slice(i, i + BATCH_SIZE);
|
|
await Promise.all(
|
|
batch.map(async (url) => {
|
|
try {
|
|
const response = await fetch(url, { mode: 'cors' });
|
|
if (response.ok) {
|
|
await cache.put(url, response);
|
|
}
|
|
} catch (err) {
|
|
console.warn(`Failed to precache tile: ${url}`, err);
|
|
} finally {
|
|
loaded++;
|
|
setCacheProgress({ loaded, total: tileUrls.length });
|
|
}
|
|
})
|
|
);
|
|
}
|
|
} catch (err) {
|
|
console.error('Error opening tile cache:', err);
|
|
} finally {
|
|
setIsCaching(false);
|
|
}
|
|
}, [tileUrlTemplate]);
|
|
|
|
return (
|
|
<div className={styles.mapWrapper}>
|
|
{/*<div className={styles.controlOverlay}>
|
|
<button
|
|
className={styles.precacheButton}
|
|
onClick={precacheCurrentRegion}
|
|
disabled={isCaching}
|
|
>
|
|
{isCaching ? 'Downloading Area...' : 'Precache Region for Offline'}
|
|
</button>
|
|
|
|
{cacheProgress && cacheProgress.total > 0 && (
|
|
<div className={styles.progressContainer}>
|
|
<span>
|
|
{cacheProgress.loaded} / {cacheProgress.total} tiles saved
|
|
</span>
|
|
<div className={styles.progressBar}>
|
|
<div
|
|
className={styles.progressFill}
|
|
style={{
|
|
width: `${Math.round((cacheProgress.loaded / cacheProgress.total) * 100)}%`,
|
|
}}
|
|
/>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>*/}
|
|
|
|
<div ref={mapContainerRef} className={styles.mapContainer} />
|
|
</div>
|
|
);
|
|
} |