You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
69 lines
2.3 KiB
TypeScript
69 lines
2.3 KiB
TypeScript
import { Marker } from 'leaflet';
|
|
import { buildOptions, numAttr, buildAttrMap, setLayerAttr } from '../core/utils.ts';
|
|
import { withProps } from '../core/with-props.ts';
|
|
|
|
import { registerChildren, unregisterChildren } from '../core/register.ts';
|
|
import type { PropDef } from '../core/props.ts';
|
|
|
|
const PROPS = {
|
|
lat: { kind: 'num', attr: 'lat', default: 0 },
|
|
lng: { kind: 'num', attr: 'lng', default: 0 },
|
|
title: { kind: 'str', attr: 'title', default: '' },
|
|
alt: { kind: 'str', attr: 'alt', default: '' },
|
|
draggable: { kind: 'bool-on', attr: 'draggable' },
|
|
opacity: { kind: 'num', attr: 'opacity', default: 1.0 },
|
|
zIndexOffset: { kind: 'num', attr: 'z-index-offset', default: 0 },
|
|
} satisfies Record<string, PropDef>;
|
|
|
|
const PROP_BY_ATTR = buildAttrMap(PROPS);
|
|
|
|
export default class LeafletMarker extends withProps(HTMLElement, PROPS) {
|
|
#obj?: Marker;
|
|
#syncing = false;
|
|
|
|
connectedCallback() {
|
|
this.#obj = new Marker(
|
|
[numAttr(this, PROPS, 'lat'), numAttr(this, PROPS, 'lng')],
|
|
buildOptions(this, PROPS, ['lat', 'lng']),
|
|
);
|
|
this.#obj.on('dragend', this.#onDragEnd);
|
|
registerChildren(this, this.#obj);
|
|
}
|
|
|
|
disconnectedCallback() {
|
|
this.#obj?.off('dragend', this.#onDragEnd);
|
|
unregisterChildren(this);
|
|
this.#obj?.remove();
|
|
this.#obj = undefined;
|
|
}
|
|
|
|
attributeChangedCallback(name: string, _old: string | null, val: string | null) {
|
|
if (!this.#obj || this.#syncing) return;
|
|
if (name === 'lat' || name === 'lng') {
|
|
this.#obj.setLatLng([numAttr(this, PROPS, 'lat'), numAttr(this, PROPS, 'lng')]);
|
|
} else if (name === 'draggable') {
|
|
if (val !== null) this.#obj.dragging?.enable();
|
|
else this.#obj.dragging?.disable();
|
|
} else if (name === 'title') {
|
|
const el = this.#obj.getElement();
|
|
if (el) (el as HTMLImageElement).title = val ?? '';
|
|
} else if (name === 'alt') {
|
|
const el = this.#obj.getElement();
|
|
if (el) (el as HTMLImageElement).alt = val ?? '';
|
|
} else {
|
|
setLayerAttr(this.#obj!, PROPS, PROP_BY_ATTR, name, val);
|
|
}
|
|
}
|
|
|
|
#onDragEnd = () => {
|
|
if (!this.#obj || this.#syncing) return;
|
|
this.#syncing = true;
|
|
const pos = this.#obj.getLatLng();
|
|
this.setAttribute('lat', String(pos.lat));
|
|
this.setAttribute('lng', String(pos.lng));
|
|
this.#syncing = false;
|
|
};
|
|
}
|
|
|
|
customElements.define('leaflet-marker', LeafletMarker);
|