leaflet#Map TypeScript Examples

The following examples show how to use leaflet#Map. 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
export default class LiveAtlasLeafletMap extends Map {
	declare _controlCorners: any;
	declare	_controlContainer?: HTMLElement;
	declare	_container?: HTMLElement;

	private readonly _layerManager: LayerManager;

	constructor(element: string | HTMLElement, options?: MapOptions) {
		super(element, options);

		this._layerManager = Object.seal(new LayerManager(this));
	}

	getLayerManager(): LayerManager {
		return this._layerManager;
	}

	// 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: 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 #3
Source File: LoadingControl.ts    From LiveAtlas with Apache License 2.0 6 votes vote down vote up
onAdd(map: Map) {
		this._loadingIndicator.title = useStore().state.messages.loadingTitle;
		this._loadingIndicator.hidden = true;
		this._loadingIndicator.innerHTML = `
		<svg class="svg-icon">
		  <use xlink:href="#icon--loading" />
		</svg>`;

		this._addLayerListeners(map);
		this._addMapListeners(map);

		return this._loadingIndicator;
	}
Example #4
Source File: LoadingControl.ts    From LiveAtlas with Apache License 2.0 6 votes vote down vote up
_addLayerListeners(map: Map) {
		// Add listeners for begin and end of load to any layers already
		// on the map
		map.eachLayer((layer: Layer) => {
			if(!(layer instanceof TileLayer)) {
				return;
			}

			if(layer.isLoading()) {
				this.addLoader((layer as any)._leaflet_id);
			}

			layer.on('loading', this._handleLoading, this);
			layer.on('load', this._handleLoad, this);
		});

		// When a layer is added to the map, add listeners for begin and
		// end of load
		map.on('layeradd', this._layerAdd, this);
		map.on('layerremove', this._layerRemove, this);
	}
Example #5
Source File: LoadingControl.ts    From LiveAtlas with Apache License 2.0 6 votes vote down vote up
_removeLayerListeners(map: Map) {
		// Remove listeners for begin and end of load from all layers
		map.eachLayer((layer: Layer) => {
			if(!(layer instanceof TileLayer)) {
				return;
			}

			this.removeLoader((layer as any)._leaflet_id);

			layer.off('loading', this._handleLoading, this);
			layer.off('load', this._handleLoad, this);
		});

		// Remove layeradd/layerremove listener from map
		map.off('layeradd', this._layerAdd, this);
		map.off('layerremove', this._layerRemove, this);
	}
Example #6
Source File: LoadingControl.ts    From LiveAtlas with Apache License 2.0 6 votes vote down vote up
_addMapListeners(map: Map) {
		// Add listeners to the map for (custom) dataloading and dataload
		// events, eg, for AJAX calls that affect the map but will not be
		// reflected in the above layer events.
		map.on('baselayerchange', this._handleBaseLayerChange, this);
		map.on('dataloading', this._handleLoading, this);
		map.on('dataload', this._handleLoad, this);
		map.on('layerremove', this._handleLoad, this);
	}
Example #7
Source File: LayerManager.ts    From LiveAtlas with Apache License 2.0 6 votes vote down vote up
constructor(map: Map) {
		const showControl = computed(() => useStore().state.components.layerControl);
		this.map = map;
		this.layerControl = new LiveAtlasLayerControl({}, {},{
			position: 'topleft',
		});

		if(showControl.value) {
			this.map.addControl(this.layerControl);
		}

		watch(showControl, (show) => {
			if(show) {
				this.map.addControl(this.layerControl);
			} else {
				this.map.removeControl(this.layerControl);
			}
		})
	}
Example #8
Source File: PlayerMarker.ts    From LiveAtlas with Apache License 2.0 6 votes vote down vote up
onRemove(map: Map): this {
		if(this._playerUnwatch) {
			this._playerUnwatch();
		}

		if(this._imageUrlUnwatch) {
			this._imageUrlUnwatch();
		}

		if(this._icon) {
			this._PlayerIcon.detach();
		}

		return super.onRemove(map);
	}
Example #9
Source File: CoordinatesControl.ts    From LiveAtlas with Apache License 2.0 5 votes vote down vote up
declare _map ?: Map;
Example #10
Source File: LoadingControl.ts    From LiveAtlas with Apache License 2.0 5 votes vote down vote up
onRemove(map: Map) {
		this._removeLayerListeners(map);
		this._removeMapListeners(map);
	}
Example #11
Source File: LoadingControl.ts    From LiveAtlas with Apache License 2.0 5 votes vote down vote up
_removeMapListeners(map: Map) {
		map.off('baselayerchange', this._handleBaseLayerChange, this);
		map.off('dataloading', this._handleLoading, this);
		map.off('dataload', this._handleLoad, this);
		map.off('layerremove', this._handleLoad, this);
	}
Example #12
Source File: LayerManager.ts    From LiveAtlas with Apache License 2.0 5 votes vote down vote up
private readonly map: Map;
Example #13
Source File: GenericMarker.ts    From LiveAtlas with Apache License 2.0 5 votes vote down vote up
onRemove(map: Map): this {
		this.options.icon.removeLabel();

		super.onRemove(map);

		return this;
	}
Example #14
Source File: PlayerMarker.ts    From LiveAtlas with Apache License 2.0 5 votes vote down vote up
onAdd(map: Map) {
		const imageUrl = computed(() => useStore().state.components.players.imageUrl);

		this._playerUnwatch = watch(this._player, () => this._PlayerIcon.update(), {deep: true});
		this._imageUrlUnwatch = watch(imageUrl, () => nextTick(() => this._PlayerIcon.updateImage()));

		return super.onAdd(map);
	}
Example #15
Source File: map.component.ts    From mylog14 with GNU General Public License v3.0 5 votes vote down vote up
onMapReady(map: Map) {
    timer(50).pipe(
      tap(() => map.invalidateSize()),
      takeUntil(this.destroy$),
    ).subscribe();
  }
Example #16
Source File: Maps.tsx    From roamjs-com with MIT License 4 votes vote down vote up
Maps = ({ blockId }: { blockId: string }): JSX.Element => {
  const id = useMemo(() => `roamjs-maps-container-id-${blockId}`, [blockId]);
  const mapInstance = useRef<Map>(null);
  const initialTree = useTreeByHtmlId(blockId);
  const [height, setHeight] = useState(DEFAULT_HEIGHT);
  const fixHeight = useCallback(() => {
    setHeight(
      parseInt(
        getComputedStyle(document.getElementById(id)).width.match(
          /^(.*)px$/
        )?.[1] || `${Math.round((DEFAULT_HEIGHT * 4) / 3)}`
      ) * 0.75
    );
    mapInstance.current?.invalidateSize?.();
  }, [setHeight]);
  const initialZoom = useMemo(() => getZoom(initialTree), [initialTree]);
  const initialCenter = useMemo(() => getCenter(initialTree), [initialTree]);
  const [markers, setMarkers] = useState<RoamMarker[]>([]);
  const [loaded, setLoaded] = useState(false);
  const [filter, setFilter] = useState(getFilter(initialTree));
  const isShift = useRef(false);
  const load = useCallback(() => setLoaded(true), [setLoaded]);
  const refresh = useCallback(() => {
    const tree = getTreeByHtmlId(blockId);
    mapInstance.current.setZoom(getZoom(tree));
    mapInstance.current.panTo(getCenter(tree));
    setFilter(getFilter(tree));
    getMarkers(tree).then((newMarkers) => {
      setMarkers(newMarkers);
    });
    fixHeight();
  }, [mapInstance, setMarkers, blockId, fixHeight]);

  const [href, setHref] = useState("https://roamresearch.com");
  useEffect(() => {
    const windowHref = window.location.href;
    setHref(
      windowHref.includes("/page/")
        ? windowHref.substring(0, windowHref.indexOf("/page/"))
        : windowHref
    );
  }, [setHref]);
  const shiftKeyCallback = useCallback(
    (e: KeyboardEvent) => (isShift.current = e.shiftKey),
    [isShift]
  );
  useEffect(() => {
    if (!loaded) {
      load();
      getMarkers(initialTree).then((newMarkers) => {
        setMarkers(newMarkers);
      });
      document.addEventListener("keydown", shiftKeyCallback);
      document.addEventListener("keyup", shiftKeyCallback);
      fixHeight();
    }
  }, [load, loaded, initialTree, setMarkers, shiftKeyCallback, id, fixHeight]);
  const filteredMarkers = useMemo(
    () =>
      filter
        ? markers.filter((m) =>
            isTagOnPage({ tag: filter, title: extractTag(m.tag) })
          )
        : markers,
    [markers, filter]
  );
  const filterOnBlur = useCallback(
    (value: string) => {
      setInputSetting({
        blockUid: getUidsFromId(blockId).blockUid,
        value,
        key: "filter",
      });
      setFilter(value);
    },
    [blockId]
  );
  const whenCreated = useCallback(
    (m) => {
      mapInstance.current = m;
      mapInstance.current.invalidateSize();
    },
    [mapInstance]
  );
  return (
    <EditContainer
      blockId={blockId}
      refresh={refresh}
      Settings={
        <>
          <Label>
            Filter
            <PageInput
              value={filter}
              setValue={setFilter}
              onBlur={filterOnBlur}
            />
          </Label>
        </>
      }
    >
      <MapContainer
        center={initialCenter}
        zoom={initialZoom}
        id={id}
        style={{ height }}
        whenCreated={whenCreated}
      >
        <LayersControl position="bottomleft">
          <LayersControl.BaseLayer checked name="Streets">
            <TileLayer
              attribution='Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>'
              url="https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}"
              accessToken={process.env.MAPBOX_TOKEN}
              id="mapbox/streets-v11"
            />
          </LayersControl.BaseLayer>
          <LayersControl.BaseLayer name="Outdoors">
            <TileLayer
              attribution='Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>'
              url="https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}"
              accessToken={process.env.MAPBOX_TOKEN}
              id="mapbox/outdoors-v11"
            />
          </LayersControl.BaseLayer>
          <LayersControl.BaseLayer name="Light">
            <TileLayer
              attribution='Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>'
              url="https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}"
              accessToken={process.env.MAPBOX_TOKEN}
              id="mapbox/light-v10"
            />
          </LayersControl.BaseLayer>
          <LayersControl.BaseLayer name="Dark">
            <TileLayer
              attribution='Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>'
              url="https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}"
              accessToken={process.env.MAPBOX_TOKEN}
              id="mapbox/dark-v10"
            />
          </LayersControl.BaseLayer>
          <LayersControl.BaseLayer name="Satellite">
            <TileLayer
              attribution='Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>'
              url="https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}"
              accessToken={process.env.MAPBOX_TOKEN}
              id="mapbox/satellite-v9"
            />
          </LayersControl.BaseLayer>
        </LayersControl>
        <Markers href={href} markers={filteredMarkers} id={id} />
      </MapContainer>
    </EditContainer>
  );
}