53 lines
1.2 KiB
TypeScript
53 lines
1.2 KiB
TypeScript
|
|
import L from "leaflet";
|
||
|
|
|
||
|
|
const DEFAULT_CENTER: L.LatLngTuple = [51.505, -0.09];
|
||
|
|
const DEFAULT_ZOOM = 13;
|
||
|
|
const STORAGE_KEY = "annotatemap-view";
|
||
|
|
|
||
|
|
let map: L.Map;
|
||
|
|
|
||
|
|
interface StoredView {
|
||
|
|
lat: number;
|
||
|
|
lng: number;
|
||
|
|
zoom: number;
|
||
|
|
}
|
||
|
|
|
||
|
|
export function initMap(): L.Map {
|
||
|
|
const saved = loadView();
|
||
|
|
const center: L.LatLngTuple = saved ? [saved.lat, saved.lng] : DEFAULT_CENTER;
|
||
|
|
const zoom = saved ? saved.zoom : DEFAULT_ZOOM;
|
||
|
|
|
||
|
|
map = L.map("map").setView(center, zoom);
|
||
|
|
|
||
|
|
L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
|
||
|
|
attribution:
|
||
|
|
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
|
||
|
|
maxZoom: 19,
|
||
|
|
}).addTo(map);
|
||
|
|
|
||
|
|
map.on("moveend", () => {
|
||
|
|
const c = map.getCenter();
|
||
|
|
saveView({ lat: c.lat, lng: c.lng, zoom: map.getZoom() });
|
||
|
|
});
|
||
|
|
|
||
|
|
return map;
|
||
|
|
}
|
||
|
|
|
||
|
|
function loadView(): StoredView | null {
|
||
|
|
const raw = localStorage.getItem(STORAGE_KEY);
|
||
|
|
if (!raw) return null;
|
||
|
|
try {
|
||
|
|
return JSON.parse(raw);
|
||
|
|
} catch {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
function saveView(view: StoredView): void {
|
||
|
|
localStorage.setItem(STORAGE_KEY, JSON.stringify(view));
|
||
|
|
}
|
||
|
|
|
||
|
|
export function getMap(): L.Map {
|
||
|
|
return map;
|
||
|
|
}
|