leaflet#DomUtil TypeScript Examples

The following examples show how to use leaflet#DomUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LiveAtlasLeafletMap.ts    From LiveAtlas with Apache License 2.0 6 votes vote down vote up
// noinspection JSUnusedGlobalSymbols
	_initControlPos() {
		const corners: any = this._controlCorners = {},
			l = 'leaflet-',
			container = this._controlContainer =
				DomUtil.create('div', l + 'control-container', this._container);

		function createCorner(vSide: string, hSide: string) {
			const className = l + vSide + ' ' + l + hSide;

			corners[`${vSide}${hSide}`] = DomUtil.create('div', className, container);
		}

		createCorner('top', 'left');
		createCorner('top', 'right');
		createCorner('top', 'center');
		createCorner('bottom', 'center');
		createCorner('bottom', 'left');
		createCorner('bottom', 'right');
	}
Example #2
Source File: ChatControl.ts    From LiveAtlas with Apache License 2.0 6 votes vote down vote up
onAdd() {
		const store = useStore(),
			chatButton = DomUtil.create('button',
				'leaflet-control-bottom leaflet-control-button leaflet-control-chat') as HTMLButtonElement;

		chatButton.type = 'button';
		chatButton.title = store.state.messages.chatTitle;
		chatButton.innerHTML = `
		<svg class="svg-icon">
		  <use xlink:href="#icon--chat" />
		</svg>`;

		chatButton.addEventListener('click', e => {
			store.commit(MutationTypes.TOGGLE_UI_ELEMENT_VISIBILITY, 'chat');
			e.stopPropagation();
			e.preventDefault();
		});

		//Open chat on ArrowRight from button
		DomEvent.on(chatButton,'keydown', (e: Event) => {
			if((e as KeyboardEvent).key === 'ArrowRight') {
				store.commit(MutationTypes.SET_UI_ELEMENT_VISIBILITY, {element: 'chat', state: true});
			}
		});

		watch(store.state.ui.visibleElements, (newValue) => {
			chatButton.setAttribute('aria-expanded', newValue.has('chat').toString());
		});

		return chatButton;
	}
Example #3
Source File: ClockControl.ts    From LiveAtlas with Apache License 2.0 6 votes vote down vote up
onAdd() {
		const digital = !this.options.showTimeOfDay && !this.options.showWeather && this.options.showDigitalClock,
			worldState = useStore().state.currentWorldState;

		this._container = DomUtil.create('div', 'clock' + (digital ? ' clock--digital' : ''));
		this._sun = DomUtil.create('div', 'clock__sun', this._container);
		this._moon = DomUtil.create('div', 'clock__moon', this._container);

		this._sun.style.transform = 'translate(-150px, -150px)';
		this._moon.style.transform = 'translate(-150px, -150px)';

		this._sun!.innerHTML = `
		<svg class="svg-icon" aria-hidden="true">
	  		<use xlink:href="#icon--clock_sun" />
		</svg>`;
		this._moon!.innerHTML = `
		<svg class="svg-icon" aria-hidden="true">
	  		<use xlink:href="#icon--clock_moon" />
		</svg>`;

		if (this.options.showDigitalClock) {
			this._clock = DomUtil.create('div', 'clock__time', this._container)
		}

		this._unwatchHandler = watch(worldState, (newValue) => {
			this._update(newValue);
		}, { deep: true });

		return this._container;
	}
Example #4
Source File: CoordinatesControl.ts    From LiveAtlas with Apache License 2.0 6 votes vote down vote up
onAdd(map: Map) {
		const container = DomUtil.create('div', 'leaflet-control-coordinates');

		this._coordsContainer.textContent = this.options.showY ? '-----, ---, -----' : '-----, -----';
		this._coordsContainer.dataset.label = this.options.label;
		container.appendChild(this._coordsContainer);

		if (this.options.showRegion) {
			this._regionContainer.textContent = '--------------';
			this._regionContainer.dataset.label = store.state.messages.locationRegion;
			container.appendChild(this._regionContainer);
		}

		if (this.options.showChunk) {
			this._chunkContainer.textContent = '----, ----';
			this._chunkContainer.dataset.label = store.state.messages.locationChunk;
			container.appendChild(this._chunkContainer);
		}

		map.on('mousemove', this._onMouseMove, this);
		map.on('mouseout', this._onMouseOut, this);

		return container;
	}
Example #5
Source File: CoordinatesControl.ts    From LiveAtlas with Apache License 2.0 6 votes vote down vote up
constructor(options: CoordinatesControlOptions) {
		super(options);

		this._coordsContainer = DomUtil.create('span', 'value coordinates');
		this._chunkContainer = DomUtil.create('span', 'value chunk');
		this._regionContainer = DomUtil.create('span', 'value region');

		options.position = 'bottomleft';
		Util.setOptions(this, options);
	}
Example #6
Source File: LinkControl.ts    From LiveAtlas with Apache License 2.0 6 votes vote down vote up
onAdd() {
		const store = useStore(),
			linkButton = DomUtil.create('button',
				'leaflet-control-button leaflet-control-link') as HTMLButtonElement,
			copySuccessMessage = computed(() => store.state.messages.copyToClipboardSuccess),
			copyErrorMessage = computed(() => store.state.messages.copyToClipboardError);

		linkButton.type = 'button';
		linkButton.title = store.state.messages.linkTitle;
		linkButton.innerHTML = `
		<svg class="svg-icon" aria-hidden="true">
		  <use xlink:href="#icon--link" />
		</svg>`;

		linkButton.addEventListener('click', e => {
			e.preventDefault();
			toClipboard(window.location.href.split("#")[0] + store.getters.url).then(() => {
				notify(copySuccessMessage.value);
			}).catch((e) => {
				notify({ type: 'error', text: copyErrorMessage.value });
				console.error('Error copying to clipboard', e);
			});

		});

		return linkButton;
	}
Example #7
Source File: LogoControl.ts    From LiveAtlas with Apache License 2.0 6 votes vote down vote up
onAdd() {
		const container = DomUtil.create('div', 'leaflet-control-logo');
		let link;

		if (this.options.url) {
			link = DomUtil.create('a', '', container) as HTMLAnchorElement;
			link.href = this.options.url;
			link.setAttribute('aria-label', this.options.text);
		}

		if (this.options.image) {
			const image = DomUtil.create('img', '', link) as HTMLImageElement;
			image.src = this.options.image;
			image.alt = this.options.text;
		} else {
			container.textContent = this.options.text;
		}

		return container;
	}
Example #8
Source File: GenericIcon.ts    From LiveAtlas with Apache License 2.0 6 votes vote down vote up
createIcon(oldIcon: HTMLElement) {
		if (oldIcon) {
			DomUtil.remove(oldIcon);
		}

		const div = markerContainer.cloneNode(false) as HTMLDivElement;
		this._image = markerIcon.cloneNode(false) as HTMLImageElement;

		div.appendChild(this._image);
		div.classList.add('marker', 'leaflet-marker-icon');

		if(this.options.className) {
			div.classList.add(this.options.className);
		}

		//Create label lazily on hover
		this._image.addEventListener('mouseover', this._onHover);

		this._container = div;
		this.update();

		return div;
	}
Example #9
Source File: LiveAtlasTileLayer.ts    From LiveAtlas with Apache License 2.0 6 votes vote down vote up
protected constructor(options: LiveAtlasTileLayerOptions) {
		super('', {
			errorTileUrl: 'images/blank.png',
			zoomReverse: true,
			tileSize: options.tileSize,
			maxNativeZoom: options.nativeZoomLevels,
			minZoom: options.minZoom,
			maxZoom: options.maxZoom || options.nativeZoomLevels + (options.extraZoomLevels || 0),
		});

		Util.setOptions(this, {
			imageFormat: options.imageFormat,
			baseUrl: options.baseUrl,
			tileUpdateInterval: options.tileUpdateInterval,
			nightAndDay: !!options.nightAndDay,
			prefix: options.prefix || '',
			extraZoomLevels: options.extraZoomLevels || 0,
			nativeZoomLevels: options.nativeZoomLevels,
		});

		this.tileTemplate = DomUtil.create('img', 'leaflet-tile') as LiveAtlasTileElement;
		this.tileTemplate.style.width = this.tileTemplate.style.height = this.options.tileSize + 'px';
		this.tileTemplate.alt = '';
		this.tileTemplate.tileName = '';
		this.tileTemplate.callback = falseFn;
		this.tileTemplate.setAttribute('role', 'presentation');

		if(this.options.crossOrigin || this.options.crossOrigin === '') {
			this.tileTemplate.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
		}

		Object.seal(this.tileTemplate);
	}
Example #10
Source File: LiveAtlasLayerControl.ts    From LiveAtlas with Apache License 2.0 5 votes vote down vote up
_initLayout() {
		const className = 'leaflet-control-layers',
			container = this._container = DomUtil.create('div', className),
			section = this._section = DomUtil.create('section', className + '-list'),
			button = this._layersButton = DomUtil.create('button', className + '-toggle', container);

		DomEvent.disableClickPropagation(container);
		DomEvent.disableScrollPropagation(container);

		//Open layer list on ArrowRight from button
		DomEvent.on(button,'keydown', (e: Event) => {
			if((e as KeyboardEvent).key === 'ArrowRight') {
				store.commit(MutationTypes.SET_UI_ELEMENT_VISIBILITY, {element: 'layers', state: true});
			}
		});

		DomEvent.on(container, 'keydown', (e: Event) => {
			//Close layer list on ArrowLeft from within list
			if((e as KeyboardEvent).key === 'ArrowLeft') {
				e.preventDefault();
				store.commit(MutationTypes.SET_UI_ELEMENT_VISIBILITY, {element: 'layers', state: false});
				nextTick(() => button.focus());
			}

			const elements = Array.from(container.querySelectorAll('input')) as HTMLElement[];
			handleKeyboardEvent(e as KeyboardEvent, elements);
		});
		DomEvent.on(button,'click', () => store.commit(MutationTypes.TOGGLE_UI_ELEMENT_VISIBILITY, 'layers'));

		section.style.display = 'none';

		button.title = store.state.messages.layersTitle;
		button.setAttribute('aria-expanded', 'false');
		button.innerHTML = `
			<svg class="svg-icon" aria-hidden="true">
			  <use xlink:href="#icon--layers" />
			</svg>`;


		//Use vuex track expanded state
		watch(store.state.ui.visibleElements, (newValue) => {
			if(newValue.has('layers') && !this.visible) {
				this.expand();
			} else if(this.visible && !newValue.has('layers')) {
				this.collapse();
			}

			this.visible = store.state.ui.visibleElements.has('layers');
		});

		watch(store.state.messages, (newValue) => (button.title = newValue.layersTitle));//

		this.visible = store.state.ui.visibleElements.has('layers');

		if (this.visible) {
			this.expand();
		}

		this._baseLayersList = DomUtil.create('div', className + '-base', section);
		this._separator = DomUtil.create('div', className + '-separator', section);
		this._overlaysList = DomUtil.create('div', className + '-overlays', section);

		container.appendChild(section);

		window.addEventListener('resize', () => this.handleResize());
		this.handleResize();
	}
Example #11
Source File: LoadingControl.ts    From LiveAtlas with Apache License 2.0 5 votes vote down vote up
constructor(options: LoadingControlOptions) {
		super(options);

		this._loadingIndicator = DomUtil.create('div',
			'leaflet-control-button leaflet-control-loading') as HTMLDivElement;
	}
Example #12
Source File: LoginControl.ts    From LiveAtlas with Apache License 2.0 5 votes vote down vote up
constructor(options: ControlOptions) {
		super(options);

		this._button = DomUtil.create('button',
				'leaflet-control-bottom leaflet-control-button leaflet-control-login') as HTMLButtonElement;

		this._button.type = 'button';

		this._button.addEventListener('click', async e => {
			e.stopPropagation();
			e.preventDefault();

			await this.handleClick();
		});

		//Open login on ArrowRight from button
		DomEvent.on(this._button,'keydown', async (e: Event) => {
			if ((e as KeyboardEvent).key === 'ArrowRight') {
				e.stopPropagation();
				e.preventDefault();

				await this.handleClick();
			}
		});

		watch(this.loggedIn, () => {
			this.update();
		});

		const visibleModal = computed(() => this.store.state.ui.visibleModal);

		watch(visibleModal, (newValue, oldValue) => {
			this._button.setAttribute('aria-expanded', (newValue === 'login').toString());

			if(this._map && !newValue && oldValue === 'login') {
				this._button.focus();
			}
		});

		this.update();
	}
Example #13
Source File: rendering.ts    From squadlanes with GNU Affero General Public License v3.0 4 votes vote down vote up
export function resetMap(layerData: LayerData) {
  // remove existing map data
  if (map !== null) {
    map.remove();
    renderInfos = new Map();
    capturePointByCircleMarker = new Map();
    circleMarkerByCapturePoint = new Map();
  }

  const bounds = layerData.background.corners;

  const baseBounds = [
    [bounds[0].y, bounds[0].x],
    [bounds[1].y, bounds[1].x],
  ];
  const width = Math.abs(bounds[0].x - bounds[1].x);
  const height = Math.abs(bounds[0].y - bounds[1].y);

  const up_left_x = Math.min(bounds[0].x, bounds[1].x);
  const up_left_y = Math.min(bounds[0].y, bounds[1].y);

  const zoomOffset = 0;
  let tileSize = 256;

  const x_stretch = tileSize / width;
  const y_stretch = tileSize / height;

  const crs = extend({}, CRS.Simple, {
    // Move origin to upper left corner of map
    // need to do this because TileLayer always puts the left-upper corner on the origin
    transformation: new Transformation(
      x_stretch,
      -up_left_x * x_stretch,
      y_stretch,
      -up_left_y * y_stretch
    ),
  });

  map = leafletMap("map", {
    crs: crs,
    minZoom: 0,
    maxZoom: 6,
    zoomSnap: 0.1,
    zoomDelta: 1.0,
    dragging: true,
    boxZoom: true,
    scrollWheelZoom: true,
    touchZoom: true,
    zoomControl: true,
    doubleClickZoom: false,
    attributionControl: false,
  });

  // @ts-ignore
  map.fitBounds(baseBounds);
  map.createPane("cp");
  map.getPane("cp")!.style.zIndex = "20";
  map.createPane("cpTooltip");
  map.getPane("cpTooltip")!.style.zIndex = "30";
  map.createPane("confirmationLines");
  map.getPane("confirmationLines")!.style.zIndex = "10";
  map.createPane("background");
  map.getPane("background")!.style.zIndex = "0";

  new TileLayer(
    `map-tiles/${layerData.background.minimap_filename}/{z}/{x}/{y}.png`,
    {
      tms: false,
      maxNativeZoom: 4,
      zoomOffset: zoomOffset,
      // scale tiles to match minimap width and height
      tileSize: tileSize,
      pane: "background",
      // @ts-ignore
      bounds: baseBounds,
    }
  ).addTo(map);

  // create markers for capture points
  mapData.capturePoints.forEach((cp) => {
    const cm = circleMarker(cp.pos, {
      radius: 20,
      pane: "cp",
    });

    // remember mapping between CircleMarker and CapturePoint
    circleMarkerByCapturePoint.set(cp, cm);
    capturePointByCircleMarker.set(cm, cp);

    // during mouseover, the font color and size changes
    // (we add a CSS class and re-open the tooltip)
    cm.on("mouseover", (ev) => {
      const tt = cm.getTooltip();
      if (tt !== undefined) {
        // this will probably break at some point
        // @ts-ignore
        DomUtil.addClass(tt._container, "mouseover");
      }
      // re-open tooltip to make sure text is still centered
      cm.closeTooltip();
      cm.openTooltip();
    });
    cm.on("mouseout", (ev) => {
      const tt = cm.getTooltip();
      if (tt !== undefined) {
        // @ts-ignore
        L.DomUtil.removeClass(tt._container, "mouseover");
      }
      cm.closeTooltip();
      cm.openTooltip();
    });
  });

  // make sure the leaflet map rescales properly when the window is resized
  const mapDiv = document.getElementById("map")!;
  new ResizeObserver(() => {
    map!.invalidateSize();
    // @ts-ignore
    map!.fitBounds(baseBounds, {
      animate: false,
    });
  }).observe(mapDiv);

  // Debug
  if (window.location.hostname.startsWith("dev.")) {
    map.addEventListener("mousedown", function (ev) {
      // @ts-ignore
      const lat = ev.latlng.lat;
      // @ts-ignore
      const lng = ev.latlng.lng;
    });
  }
}