leaflet#LeafletEvent TypeScript Examples

The following examples show how to use leaflet#LeafletEvent. 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: LoadingControl.ts    From LiveAtlas with Apache License 2.0 6 votes vote down vote up
_handleBaseLayerChange (e: LeafletEvent) {
		// Check for a target 'layer' that contains multiple layers, such as
		// L.LayerGroup. This will happen if you have an L.LayerGroup in an
		// L.Control.Layers.
		if (e.layer && e.layer.eachLayer && typeof e.layer.eachLayer === 'function') {
			e.layer.eachLayer((layer: Layer) => {
				this._handleBaseLayerChange({ layer: layer } as LeafletEvent);
			});
		}
	}
Example #2
Source File: LoadingControl.ts    From LiveAtlas with Apache License 2.0 6 votes vote down vote up
_layerAdd(e: LeafletEvent) {
		if(!(e.layer instanceof TileLayer)) {
			return;
		}

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

			e.layer.on('loading', this._handleLoading, this);
			e.layer.on('load', this._handleLoad, this);
		} catch (exception) {
			console.warn('L.Control.Loading: Tried and failed to add ' +
				' event handlers to layer', e.layer);
			console.warn('L.Control.Loading: Full details', exception);
		}
	}
Example #3
Source File: LoadingControl.ts    From LiveAtlas with Apache License 2.0 6 votes vote down vote up
_layerRemove(e: LeafletEvent) {
		if(!(e.layer instanceof TileLayer)) {
			return;
		}

		try {
			e.layer.off('loading', this._handleLoading, this);
			e.layer.off('load', this._handleLoad, this);
		} catch (exception) {
			console.warn('L.Control.Loading: Tried and failed to remove ' +
				'event handlers from layer', e.layer);
			console.warn('L.Control.Loading: Full details', exception);
		}
	}
Example #4
Source File: CoalitionLayer.tsx    From project-tauntaun with GNU Lesser General Public License v3.0 6 votes vote down vote up
export function CoalitionLayer(props: CoalitionLayerProps) {
  const { commanderMode } = AppStateContainer.useContainer();
  const { coalition } = props;

  const { lat, lon } = coalition.bullseye;
  const bullseye = new LatLng(lat, lon);

  const { sessionId, sessions } = SessionStateContainer.useContainer();
  const sessionData = sessions[sessionId];
  const sessionCoalition = sessionData ? sessionData.coalition : '';
  const showBullseye = sessionCoalition === coalition.name;

  const onMarkerDragEnd = (event: LeafletEvent) => {
    const latlng = event.target._latlng;
    if (!commanderMode) {
      return;
    }

    gameService.sendSetBullseye(coalition.name, latlng);
  };

  return (
    <CoalitionContext.Provider value={{ sessionCoalition: sessionCoalition, groupCoalition: coalition.name }}>
      {Object.keys(coalition.countries).map(countryKey => (
        <CountryLayer key={countryKey} country={coalition.countries[countryKey]} />
      ))}
      {showBullseye && (
        <BullseyeMarker
          position={bullseye}
          eventHandlers={{
            dragend: onMarkerDragEnd
          }}
          draggable={commanderMode}
        />
      )}
    </CoalitionContext.Provider>
  );
}
Example #5
Source File: LiveAtlasLayerControl.ts    From LiveAtlas with Apache License 2.0 5 votes vote down vote up
// noinspection JSUnusedGlobalSymbols
	_addItem(obj: any) {
		const container = obj.overlay ? this._overlaysList : this._baseLayersList,
			item = document.createElement('label'),
			label = document.createElement('span'),
			checked = this._map!.hasLayer(obj.layer);

		let input;

		item.className = 'layer checkbox';

		if (obj.overlay) {
			input = document.createElement('input');
			input.type = 'checkbox';
			input.className = 'leaflet-control-layers-selector';
			input.defaultChecked = checked;
		} else {
			// @ts-ignore
			input = super._createRadioElement('leaflet-base-layers_' + Util.stamp(this), checked);
		}

		input.layerId = Util.stamp(obj.layer);
		this._layerControlInputs!.push(input);
		label.textContent = obj.name;

		// @ts-ignore
		DomEvent.on(input, 'click', (e: LeafletEvent) => super._onInputClick(e), this);

		item.appendChild(input);
		item.insertAdjacentHTML('beforeend',  `
		<svg class="svg-icon" aria-hidden="true">
	  		<use xlink:href="#icon--checkbox" />
		</svg>`);
		item.appendChild(label);

		container!.appendChild(item);

		// @ts-ignore
		super._checkDisabledLayers();
		return label;
	}
Example #6
Source File: LoadingControl.ts    From LiveAtlas with Apache License 2.0 5 votes vote down vote up
_handleLoading(e: LeafletEvent) {
		this.addLoader(this.getEventId(e));
	}
Example #7
Source File: LoadingControl.ts    From LiveAtlas with Apache License 2.0 5 votes vote down vote up
_handleLoad(e: LeafletEvent) {
		this.removeLoader(this.getEventId(e));
	}
Example #8
Source File: FeatureMarker.tsx    From Teyvat.moe with GNU General Public License v3.0 5 votes vote down vote up
onSingleClick = (event: LeafletEvent) => {
  // Calls on single clicks, not double clicks.

  // Trigger the popup to display only on single clicks.
  event.target.openPopup();
}
Example #9
Source File: RouteLine.tsx    From Teyvat.moe with GNU General Public License v3.0 5 votes vote down vote up
RouteLine: FunctionComponent<RouteLineProps> = ({
  route,
  editable = false,
  allowExternalMedia = false,
}) => {
  // CSS classes.
  const classes = useStyles();

  const onCopyPermalink = () => copyPermalink(route.id);

  const title = localizeField(route?.popupTitle);
  const content = localizeField(route?.popupContent);

  const eventHandlers: LeafletEventHandlerFnMap = {
    add: (event: LeafletEvent) => {
      if (editable) {
        event.target.enableEdit();
      }
    },
  };

  return (
    <TextPath
      // Options passed to the parent Polyline.
      pathOptions={{
        color: route.routeColor ?? DEFAULT_ROUTE_COLOR,
      }}
      eventHandlers={eventHandlers}
      positions={route.coordinates}
      // Attributes passed to TextPath.setText.
      text={route.routeText ?? DEFAULT_ROUTE_TEXT}
      repeat
      attributes={{
        // Attributes to apply to the text.
        dy: '6',
        fill: route.routeColor ?? DEFAULT_ROUTE_COLOR,
        class: classes.mapRouteLineText,
      }}
    >
      {/* A modern variant of MapPopupLegacy. */}
      <Popup maxWidth={540} minWidth={192} autoPan={false} keepInView={false}>
        <Box className={classes.popupContainer}>
          {title && title !== '' ? (
            <Typography className={classes.popupTitle}>{title}</Typography>
          ) : (
            <Typography className={classes.popupTitle}>
              {f('map-ui:route-id-format', { id: route.id.slice(0, 7) })}
            </Typography>
          )}
          <Box>
            <RouteMedia media={route.popupMedia ?? ''} allowExternalMedia={allowExternalMedia} />
          </Box>
          {content && content !== '' ? (
            <SafeHTML className={classes.popupContent}>{content}</SafeHTML>
          ) : null}
          {!editable ? (
            <Box className={classes.actionContainer}>
              <Tooltip title={t('map-ui:copy-permalink')}>
                <Box className={classes.innerActionContainer}>
                  <IconButton onClick={onCopyPermalink}>
                    <LinkIcon />
                  </IconButton>
                </Box>
              </Tooltip>
            </Box>
          ) : null}
        </Box>
      </Popup>
    </TextPath>
  );
}
Example #10
Source File: index.tsx    From aqualink-app with MIT License 5 votes vote down vote up
LocationMap = ({
  markerPositionLat,
  markerPositionLng,
  updateMarkerPosition,
  classes,
}: LocationMapProps) => {
  const [zoom, setZoom] = useState<number>(INITIAL_ZOOM);

  const onZoomEnd = useCallback(
    // eslint-disable-next-line no-underscore-dangle
    (event: LeafletEvent) => setZoom(event.target._zoom as number),
    []
  );

  function updateLatLng(event: L.LeafletMouseEvent) {
    const { lat, lng } = event.latlng.wrap();
    updateMarkerPosition([lat, lng]);
  }

  function parseCoordinates(coord: string, defaultValue: number) {
    const parsed = parseFloat(coord);
    return Number.isNaN(parsed) ? defaultValue : parsed;
  }

  const markerPosition: L.LatLngTuple = [
    parseCoordinates(markerPositionLat, 37.773972),
    parseCoordinates(markerPositionLng, -122.431297),
  ];

  return (
    <Map
      center={markerPosition}
      zoom={zoom}
      className={classes.map}
      onclick={updateLatLng}
      onzoomend={onZoomEnd}
      maxBounds={mapConstants.MAX_BOUNDS}
      maxBoundsViscosity={1.0}
      minZoom={1}
    >
      <TileLayer url="https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}" />
      {markerPosition && <Marker icon={pinIcon} position={markerPosition} />}
    </Map>
  );
}
Example #11
Source File: FeatureMarker.tsx    From Teyvat.moe with GNU General Public License v3.0 4 votes vote down vote up
_FeatureMarker: FunctionComponent<FeatureMarkerProps> = ({
  marker,
  featureKey,
  icons,

  completed,
  completedAlpha,

  editable = false,
  allowExternalMedia = false,

  markFeature,
  unmarkFeature,
}) => {
  // CSS classes.
  const classes = useStyles();

  let svg = false;
  let clusterIconName = '';

  if (completed) {
    // == false sucks, but TypeScript needs it to guarantee
    // the structure of the marker icon data.
    if (icons?.done?.marker == false) {
      svg = icons?.done?.svg ?? false;
      clusterIconName = icons?.done?.clusterIcon ?? '';
    }
  } else {
    if (icons?.base?.marker == false) {
      svg = icons?.base?.svg ?? false;
      clusterIconName = icons?.base?.clusterIcon ?? '';
    }
  }

  // Build the icon for this marker. Relies on completion status.
  const icon =
    icons == null
      ? editorMarker
      : createMapIcon({
          ...(completed ? icons?.done : icons?.base),
          marker: (completed ? icons?.done?.marker : icons?.base?.marker) ?? true,
          done: !!completed,
          ext: svg ? 'svg' : 'png',
          key: (completed ? icons?.done?.key : icons?.base?.key) ?? icons?.filter ?? '',
        });

  // Build the cluster icon for the marker. Also relies on completion status.
  const clusterIcon = createClusterIcon({
    marker: (completed ? icons?.done?.marker : icons?.base?.marker) ?? true,
    extension: svg ? 'svg' : 'png',
    key: (completed ? icons?.done?.key : icons?.base?.key) ?? icons?.filter ?? '',
    clusterIcon: clusterIconName,
  });

  const onDoubleClick = (_event: LeafletEvent) => {
    // Calls on double clicks, not single clicks.

    // Mark as completed.
    if (completed) {
      unmarkFeature();
    } else {
      markFeature();
    }
  };

  const DOUBLE_CLICK_TIMEOUT = 300;

  const onCopyPermalink = () => copyPermalink(marker.id);

  const onSwitchCompleted = (value: boolean): void => {
    // If we switch to true but the marker is already completed,
    // do nothing.
    if (value === !!completed) return;

    if (value) {
      markFeature();
    } else {
      unmarkFeature();
    }
  };

  /* eslint-disable no-param-reassign */
  const eventHandlers: Record<string, LeafletEventHandlerFn> = {
    add: (event) => {
      // We will be triggering popups manually.
      event.target.off('click', event.target._openPopup);
      if (editable) {
        event.target.enableEdit();
      }
    },
    click: (event) => {
      if (event.target.clicks === undefined) event.target.clicks = 0;

      event.target.clicks += 1;

      setTimeout(() => {
        if (event.target.clicks === 1) {
          onSingleClick(event);
        }
        event.target.clicks = 0;
      }, DOUBLE_CLICK_TIMEOUT);
    },
    dblclick: (event) => {
      event.target.clicks = 0;
      onDoubleClick(event);
    },
  };
  /* eslint-enable no-param-reassign */

  const title = localizeField(marker?.popupTitle);
  const content = localizeField(marker?.popupContent);

  return (
    <ExtendedMarker
      clusterIconUrl={clusterIcon}
      completed={!!completed}
      eventHandlers={eventHandlers}
      icon={icon}
      key={marker.id}
      markerKey={`${featureKey}/${marker.id}`}
      opacity={completed ? completedAlpha : 1}
      position={marker.coordinates}
    >
      {/* A modern variant of MapPopupLegacy. */}
      <Popup maxWidth={540} minWidth={192} autoPan={false} keepInView={false}>
        <Box className={classes.popupContainer}>
          {title && title !== '' ? (
            <Typography className={classes.popupTitle}>{title}</Typography>
          ) : (
            <Typography className={classes.popupTitle}>
              {f('map-ui:marker-id-format', { id: marker.id.slice(0, 7) })}
            </Typography>
          )}
          <Box>
            <FeatureMedia media={marker.popupMedia} allowExternalMedia={allowExternalMedia} />
          </Box>
          {content && content !== '' ? (
            <SafeHTML className={classes.popupContent}>{content}</SafeHTML>
          ) : null}
          {!editable ? (
            <Box className={classes.actionContainer}>
              <Tooltip title={t('completed')}>
                <Box className={classes.innerActionContainer}>
                  <InputSwitch
                    size="small"
                    color="primary"
                    label={<AssignmentTurnedInIcon />}
                    value={Boolean(completed)}
                    onChange={onSwitchCompleted}
                  />
                </Box>
              </Tooltip>
              <Tooltip title={t('map-ui:copy-permalink')}>
                <Box className={classes.innerActionContainer}>
                  <IconButton onClick={onCopyPermalink}>
                    <LinkIcon />
                  </IconButton>
                </Box>
              </Tooltip>
            </Box>
          ) : null}
          {completed ? (
            <Typography className={classes.completedSubtitle}>
              {f('map-ui:completed-time-format', {
                time: formatUnixTimestamp(completed),
              })}
            </Typography>
          ) : null}
        </Box>
      </Popup>
    </ExtendedMarker>
  );
}