570 lines
15 KiB
TypeScript
570 lines
15 KiB
TypeScript
import {
|
|
AfterViewInit,
|
|
ChangeDetectionStrategy,
|
|
Component,
|
|
ElementRef,
|
|
HostListener,
|
|
NgZone,
|
|
OnDestroy,
|
|
ViewChild,
|
|
effect,
|
|
inject,
|
|
input,
|
|
signal,
|
|
} from '@angular/core';
|
|
import { Geolocation, type Position } from '@capacitor/geolocation';
|
|
|
|
import type { Attraction } from '../../areas/area.models';
|
|
import { Icon } from '../../shared/icon/icon';
|
|
import { MapItemSheet } from '../map-item-sheet/map-item-sheet';
|
|
|
|
const MAP_KEY = 'bf0a466f-43a6-48c7-b274-7fea5952957b';
|
|
const CITY_CENTER: [number, number] = [43.99934, 56.329399];
|
|
const CITY_ZOOM = 16;
|
|
const USER_ZOOM = 20;
|
|
const LANDMARK_SIZE = 40;
|
|
const USER_SIZE = 32;
|
|
|
|
interface DgPoint {
|
|
x: number;
|
|
y: number;
|
|
}
|
|
|
|
interface DgMarker {
|
|
addTo(map: DgMap): this;
|
|
remove(): void;
|
|
setLatLng(latLng: [number, number]): this;
|
|
setZIndexOffset(offset: number): this;
|
|
getElement(): HTMLElement | undefined;
|
|
on(type: string, handler: (event: Event) => void): this;
|
|
}
|
|
|
|
interface DgMap {
|
|
on(type: string, handler: () => void): this;
|
|
off(type: string, handler: () => void): this;
|
|
setView(
|
|
center: [number, number],
|
|
zoom: number,
|
|
options?: { animate?: boolean; duration?: number },
|
|
): this;
|
|
getZoom(): number;
|
|
latLngToContainerPoint(latLng: [number, number]): DgPoint;
|
|
invalidateSize?(): void;
|
|
remove(): void;
|
|
}
|
|
|
|
interface DgLoader {
|
|
then(resolve: () => void, reject?: (error: unknown) => void): Promise<void>;
|
|
}
|
|
|
|
interface DgApi {
|
|
map(element: HTMLElement, options: Record<string, unknown>): DgMap;
|
|
marker(latLng: [number, number], options: Record<string, unknown>): DgMarker;
|
|
divIcon(options: Record<string, unknown>): unknown;
|
|
}
|
|
|
|
declare global {
|
|
interface Window {
|
|
DG?: DgLoader & DgApi;
|
|
}
|
|
}
|
|
|
|
let rasterApi: Promise<DgApi> | null = null;
|
|
|
|
function loadRasterApi(): Promise<DgApi> {
|
|
if (rasterApi) {
|
|
return rasterApi;
|
|
}
|
|
|
|
rasterApi = new Promise<DgApi>((resolve, reject) => {
|
|
const ready = (): void => {
|
|
const api = window.DG;
|
|
|
|
if (!api) {
|
|
reject(new Error('RasterJS API не загрузился'));
|
|
return;
|
|
}
|
|
|
|
void api.then(
|
|
() => {
|
|
const readyApi = window.DG;
|
|
|
|
if (!readyApi?.map || !readyApi.marker || !readyApi.divIcon) {
|
|
reject(new Error('RasterJS API не загрузился'));
|
|
return;
|
|
}
|
|
|
|
resolve({
|
|
map: readyApi.map.bind(readyApi),
|
|
marker: readyApi.marker.bind(readyApi),
|
|
divIcon: readyApi.divIcon.bind(readyApi),
|
|
});
|
|
},
|
|
(error: unknown) => reject(error),
|
|
);
|
|
};
|
|
|
|
if (window.DG) {
|
|
ready();
|
|
return;
|
|
}
|
|
|
|
const script = document.createElement('script');
|
|
script.src = `https://maps.api.2gis.ru/2.0/loader.js?pkg=full&lazy=true&skin=dark&key=${MAP_KEY}`;
|
|
script.async = true;
|
|
script.onload = ready;
|
|
script.onerror = () => reject(new Error('Не удалось загрузить RasterJS API'));
|
|
document.body.appendChild(script);
|
|
});
|
|
|
|
return rasterApi;
|
|
}
|
|
|
|
@Component({
|
|
selector: 'app-city-map',
|
|
imports: [Icon, MapItemSheet],
|
|
templateUrl: './city-map.html',
|
|
styleUrl: './city-map.scss',
|
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
|
host: {
|
|
'[class.is-fullscreen]': 'fullscreen()',
|
|
},
|
|
})
|
|
export class CityMap implements AfterViewInit, OnDestroy {
|
|
@ViewChild('map', { static: true })
|
|
private mapElement!: ElementRef<HTMLElement>;
|
|
|
|
private readonly zone = inject(NgZone);
|
|
private raster: DgApi | null = null;
|
|
private map: DgMap | null = null;
|
|
private userMarker: DgMarker | null = null;
|
|
private userMarkerElement: HTMLElement | null = null;
|
|
private watchId: string | null = null;
|
|
private lastPosition: Position | null = null;
|
|
private zoomOnNextPan = true;
|
|
private destroyed = false;
|
|
private programmaticMove = false;
|
|
private resizeObserver: ResizeObserver | null = null;
|
|
private readonly hostRef = inject(ElementRef<HTMLElement>);
|
|
private readonly clippedAncestors: HTMLElement[] = [];
|
|
private readonly markerElements = new Map<string, HTMLElement>();
|
|
private readonly markers = new Map<string, DgMarker>();
|
|
private readonly mapReady = signal(false);
|
|
private placedKey = '';
|
|
private readonly stopFollowing = (): void => {
|
|
this.programmaticMove = false;
|
|
this.zone.run(() => this.following.set(false));
|
|
};
|
|
private readonly onZoomStart = (): void => {
|
|
if (this.programmaticMove) {
|
|
return;
|
|
}
|
|
|
|
this.stopFollowing();
|
|
};
|
|
private readonly onMoveEnd = (): void => {
|
|
this.programmaticMove = false;
|
|
};
|
|
|
|
readonly embedded = input(false);
|
|
readonly cityName = input('');
|
|
readonly areaId = input('');
|
|
readonly attractions = input<Attraction[]>([]);
|
|
|
|
protected readonly selected = signal<Attraction | null>(null);
|
|
protected readonly following = signal(false);
|
|
protected readonly fullscreen = signal(false);
|
|
|
|
constructor() {
|
|
effect(() => {
|
|
const items = this.attractions();
|
|
|
|
if (!this.mapReady()) {
|
|
return;
|
|
}
|
|
|
|
this.placeMarkers(items);
|
|
});
|
|
|
|
effect(() => {
|
|
const active = this.fullscreen();
|
|
this.setAncestorOverflow(active);
|
|
requestAnimationFrame(() => this.resizeMap());
|
|
});
|
|
}
|
|
|
|
async ngAfterViewInit(): Promise<void> {
|
|
this.resizeObserver = new ResizeObserver(() => this.resizeMap());
|
|
this.resizeObserver.observe(this.mapElement.nativeElement);
|
|
|
|
const api = await loadRasterApi();
|
|
this.raster = api;
|
|
|
|
if (this.destroyed) {
|
|
return;
|
|
}
|
|
|
|
this.zone.runOutsideAngular(() => {
|
|
const raster = this.raster;
|
|
|
|
if (this.destroyed || !raster) {
|
|
return;
|
|
}
|
|
|
|
const map = raster.map(this.mapElement.nativeElement, {
|
|
center: this.toLatLng(this.focusCenter(this.attractions())),
|
|
zoom: CITY_ZOOM,
|
|
key: MAP_KEY,
|
|
currentLang: 'ru',
|
|
zoomControl: false,
|
|
fullscreenControl: false,
|
|
poi: false,
|
|
geoclicker: false,
|
|
});
|
|
|
|
if (this.destroyed) {
|
|
map.remove();
|
|
return;
|
|
}
|
|
|
|
this.map = map;
|
|
map.on('dragstart', this.stopFollowing);
|
|
map.on('zoomstart', this.onZoomStart);
|
|
map.on('moveend', this.onMoveEnd);
|
|
|
|
this.zone.run(() => this.mapReady.set(true));
|
|
requestAnimationFrame(() => this.resizeMap());
|
|
});
|
|
}
|
|
|
|
ngOnDestroy(): void {
|
|
this.destroyed = true;
|
|
this.setAncestorOverflow(false);
|
|
this.resizeObserver?.disconnect();
|
|
void this.stopWatching();
|
|
this.map?.off('dragstart', this.stopFollowing);
|
|
this.map?.off('zoomstart', this.onZoomStart);
|
|
this.map?.off('moveend', this.onMoveEnd);
|
|
this.map?.remove();
|
|
this.map = null;
|
|
}
|
|
|
|
protected toggleFullscreen(): void {
|
|
this.fullscreen.update((active) => !active);
|
|
}
|
|
|
|
protected exitFullscreen(): void {
|
|
this.fullscreen.set(false);
|
|
}
|
|
|
|
@HostListener('document:keydown.escape')
|
|
protected onEscape(): void {
|
|
this.exitFullscreen();
|
|
}
|
|
|
|
protected focusCity(): void {
|
|
this.following.set(false);
|
|
this.clearSelection();
|
|
this.moveMap(this.focusCenter(this.attractions()), CITY_ZOOM, 500);
|
|
}
|
|
|
|
protected async locate(): Promise<void> {
|
|
if (!this.map) {
|
|
return;
|
|
}
|
|
|
|
if (this.following()) {
|
|
this.following.set(false);
|
|
return;
|
|
}
|
|
|
|
if (this.watchId && this.lastPosition) {
|
|
this.zoomOnNextPan = true;
|
|
this.following.set(true);
|
|
this.updateUserPosition(this.lastPosition, true);
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const position = await Geolocation.getCurrentPosition({
|
|
enableHighAccuracy: true,
|
|
timeout: 30_000,
|
|
});
|
|
|
|
this.zoomOnNextPan = true;
|
|
this.following.set(true);
|
|
this.updateUserPosition(position, true);
|
|
this.watchId = await Geolocation.watchPosition(
|
|
{ enableHighAccuracy: true },
|
|
(next, error) => {
|
|
if (error || !next) {
|
|
return;
|
|
}
|
|
|
|
this.zone.run(() => this.updateUserPosition(next, this.following()));
|
|
},
|
|
);
|
|
} catch {
|
|
this.following.set(false);
|
|
}
|
|
}
|
|
|
|
private updateUserPosition(position: Position, pan: boolean): void {
|
|
const map = this.map;
|
|
|
|
if (!map) {
|
|
return;
|
|
}
|
|
|
|
this.lastPosition = position;
|
|
const coordinates: [number, number] = [position.coords.longitude, position.coords.latitude];
|
|
const heading = position.coords.heading;
|
|
|
|
const raster = this.raster;
|
|
|
|
if (!this.userMarker && raster) {
|
|
const markerElement = document.createElement('div');
|
|
markerElement.className = 'city-map__user';
|
|
markerElement.innerHTML =
|
|
'<span class="city-map__user-body"><span class="city-map__user-heading"></span><span class="city-map__user-dot"></span></span>';
|
|
this.userMarkerElement = markerElement;
|
|
this.userMarker = this.addHtmlMarker(
|
|
raster,
|
|
map,
|
|
coordinates,
|
|
markerElement,
|
|
USER_SIZE,
|
|
3,
|
|
false,
|
|
);
|
|
} else {
|
|
this.userMarker?.setLatLng(this.toLatLng(coordinates));
|
|
}
|
|
|
|
if (heading != null && !Number.isNaN(heading) && this.userMarkerElement) {
|
|
this.userMarkerElement.style.setProperty('--heading', `${heading}deg`);
|
|
this.userMarkerElement.classList.add('city-map__user--headed');
|
|
}
|
|
|
|
if (pan) {
|
|
this.moveMap(coordinates, this.zoomOnNextPan ? USER_ZOOM : null, 400);
|
|
this.zoomOnNextPan = false;
|
|
}
|
|
}
|
|
|
|
private async stopWatching(): Promise<void> {
|
|
if (!this.watchId) {
|
|
return;
|
|
}
|
|
|
|
await Geolocation.clearWatch({ id: this.watchId });
|
|
this.watchId = null;
|
|
}
|
|
|
|
private placeMarkers(items: Attraction[]): void {
|
|
const map = this.map;
|
|
const api = this.raster;
|
|
|
|
if (!map || !api) {
|
|
return;
|
|
}
|
|
|
|
const key = items.map((item) => `${item.id}:${item.latitude}:${item.longitude}`).join('|');
|
|
|
|
if (key === this.placedKey) {
|
|
for (const item of items) {
|
|
const element = this.markerElements.get(item.id);
|
|
|
|
if (element) {
|
|
this.setMarkerIcon(element, item);
|
|
}
|
|
}
|
|
|
|
return;
|
|
}
|
|
|
|
for (const marker of this.markers.values()) {
|
|
marker.remove();
|
|
}
|
|
|
|
this.markers.clear();
|
|
this.markerElements.clear();
|
|
this.placedKey = key;
|
|
|
|
for (const item of items) {
|
|
if (typeof item.latitude !== 'number' || typeof item.longitude !== 'number') {
|
|
continue;
|
|
}
|
|
|
|
this.markers.set(item.id, this.createMarker(api, map, item));
|
|
}
|
|
|
|
if (this.markers.size > 0) {
|
|
this.moveMap(this.focusCenter(items), CITY_ZOOM, 0);
|
|
}
|
|
}
|
|
|
|
private createMarker(api: DgApi, map: DgMap, item: Attraction): DgMarker {
|
|
const markerElement = document.createElement('button');
|
|
markerElement.type = 'button';
|
|
markerElement.className = 'city-map__marker';
|
|
markerElement.setAttribute('aria-label', item.name);
|
|
markerElement.innerHTML = `<span></span><img width="40" height="40" alt="" /><span class="city-map__label"></span>`;
|
|
// '<span class="city-map__radius"></span><img width="40" height="40" alt="" /><span class="city-map__label"></span>';
|
|
// Marker with radius
|
|
// markerElement.innerHTML =
|
|
// '<span class="city-map__radius"></span><img width="40" height="40" alt="" /><span class="city-map__label"></span>';
|
|
const label = markerElement.querySelector('.city-map__label');
|
|
|
|
if (label) {
|
|
label.textContent = item.name;
|
|
}
|
|
|
|
this.markerElements.set(item.id, markerElement);
|
|
this.setMarkerIcon(markerElement, item);
|
|
|
|
const marker = this.addHtmlMarker(
|
|
api,
|
|
map,
|
|
[item.longitude, item.latitude],
|
|
markerElement,
|
|
LANDMARK_SIZE,
|
|
1,
|
|
true,
|
|
);
|
|
|
|
marker.on('click', () => {
|
|
this.zone.run(() => this.selectLandmark(item));
|
|
});
|
|
|
|
return marker;
|
|
}
|
|
|
|
private focusCenter(items: Attraction[]): [number, number] {
|
|
const points = items.filter(
|
|
(item) => typeof item.latitude === 'number' && typeof item.longitude === 'number',
|
|
);
|
|
|
|
if (points.length === 0) {
|
|
return CITY_CENTER;
|
|
}
|
|
|
|
const longitude = points.reduce((sum, item) => sum + item.longitude, 0) / points.length;
|
|
const latitude = points.reduce((sum, item) => sum + item.latitude, 0) / points.length;
|
|
|
|
return [longitude, latitude];
|
|
}
|
|
|
|
private addHtmlMarker(
|
|
api: DgApi,
|
|
map: DgMap,
|
|
coordinates: [number, number],
|
|
element: HTMLElement,
|
|
size: number,
|
|
zIndexOffset: number,
|
|
interactive: boolean,
|
|
): DgMarker {
|
|
const marker = api.marker(this.toLatLng(coordinates), {
|
|
icon: api.divIcon({
|
|
className: 'city-map__pin',
|
|
html: element,
|
|
iconSize: [size, size],
|
|
iconAnchor: [size / 2, size / 2],
|
|
}),
|
|
interactive,
|
|
keyboard: false,
|
|
zIndexOffset,
|
|
});
|
|
|
|
marker.addTo(map);
|
|
const root = marker.getElement();
|
|
|
|
if (root) {
|
|
root.style.overflow = 'visible';
|
|
}
|
|
|
|
return marker;
|
|
}
|
|
|
|
private setMarkerIcon(element: HTMLElement, item: Attraction): void {
|
|
const img = element.querySelector('img');
|
|
|
|
if (!img) {
|
|
return;
|
|
}
|
|
|
|
const src = item.visited ? '/assets/icons/check-marker.svg' : '/assets/icons/lock-marker.svg';
|
|
|
|
if (img.getAttribute('src') !== src) {
|
|
img.setAttribute('src', src);
|
|
}
|
|
|
|
element.classList.toggle('city-map__marker--open', item.visited);
|
|
}
|
|
|
|
private selectLandmark(landmark: Attraction): void {
|
|
const alreadySelected = this.selected()?.id === landmark.id;
|
|
this.selected.set(alreadySelected ? null : landmark);
|
|
this.syncSelection();
|
|
}
|
|
|
|
private clearSelection(): void {
|
|
this.selected.set(null);
|
|
this.syncSelection();
|
|
}
|
|
|
|
private syncSelection(): void {
|
|
const selectedId = this.selected()?.id;
|
|
|
|
for (const [id, element] of this.markerElements) {
|
|
const active = id === selectedId;
|
|
element.classList.toggle('city-map__marker--active', active);
|
|
this.markers.get(id)?.setZIndexOffset(active ? 2 : 1);
|
|
}
|
|
}
|
|
|
|
private moveMap(center: [number, number], zoom: number | null, durationMs: number): void {
|
|
const map = this.map;
|
|
|
|
if (!map) {
|
|
return;
|
|
}
|
|
|
|
this.programmaticMove = true;
|
|
map.setView(this.toLatLng(center), zoom ?? map.getZoom(), {
|
|
animate: true,
|
|
duration: durationMs / 1000,
|
|
});
|
|
}
|
|
|
|
private toLatLng(coordinates: [number, number]): [number, number] {
|
|
return [coordinates[1], coordinates[0]];
|
|
}
|
|
|
|
private resizeMap(): void {
|
|
this.map?.invalidateSize?.();
|
|
}
|
|
|
|
private setAncestorOverflow(active: boolean): void {
|
|
for (const element of this.clippedAncestors) {
|
|
element.style.overflow = '';
|
|
}
|
|
this.clippedAncestors.length = 0;
|
|
document.body.style.overflow = '';
|
|
|
|
if (!active) {
|
|
return;
|
|
}
|
|
|
|
let node = this.hostRef.nativeElement.parentElement;
|
|
|
|
while (node && node !== document.body) {
|
|
this.clippedAncestors.push(node);
|
|
node.style.overflow = 'visible';
|
|
node = node.parentElement;
|
|
}
|
|
|
|
document.body.style.overflow = 'hidden';
|
|
}
|
|
}
|