react-leaflet#useMap TypeScript Examples

The following examples show how to use react-leaflet#useMap. 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: EditorLayer.tsx    From Teyvat.moe with GNU General Public License v3.0 6 votes vote down vote up
_EditorLayer: FunctionComponent<EditorLayerProps> = ({ displayed, editorData }) => {
  const map = useMap();
  const layerReference = useRef<LeafletLayerGroup | null>(null);

  useEffect(() => {
    if (layerReference.current !== null) {
      if (displayed) {
        layerReference.current.addTo(map);
      } else {
        layerReference.current.removeFrom(map);
      }
    }
  }, [map, displayed]);

  return (
    <LayerGroup ref={layerReference}>
      {_.map(editorData, (element) => {
        return distinguishRoute(element) ? (
          <RouteLine key={element.id} route={element} editable />
        ) : (
          <FeatureMarker
            key={element.id}
            marker={element}
            featureKey={'editor' as MSFFeatureKey}
            editable
            icons={null}
            allowExternalMedia
          />
        );
      })}
    </LayerGroup>
  );
}
Example #2
Source File: RegionLabelLayer.tsx    From Teyvat.moe with GNU General Public License v3.0 6 votes vote down vote up
_RegionLabelLayer: FunctionComponent<RegionLabelLayerProps> = ({ displayed, zoomLevel }) => {
  const classes = useStyles();

  const map = useMap();
  const layerReference = useRef<GeoJSONLeaflet | null>(null);

  useEffect(() => {
    if (layerReference.current != null) {
      if (displayed) {
        layerReference.current.addTo(map);
      } else {
        layerReference.current.removeFrom(map);
      }
    }
  }, [map, displayed]);

  const pointToLayer = (featureData: Feature<Point, any>, latLng: LatLng) => {
    const html = renderToString(<RegionLabel featureData={featureData} zoomLevel={zoomLevel} />);

    return LeafletMarker([latLng.lng, latLng.lat], {
      interactive: false, // Allow clicks to pass through.
      icon: LeafletDivIcon({
        html,
        className: classes.regionLabelMarker,
      }),
      zIndexOffset: -900,
    });
  };

  return (
    <GeoJSON
      ref={layerReference}
      key={zoomLevel}
      pointToLayer={pointToLayer}
      data={RegionLabelData as GeoJsonObject}
    />
  );
}
Example #3
Source File: WorldBorderLayer.tsx    From Teyvat.moe with GNU General Public License v3.0 6 votes vote down vote up
_WorldBorderLayer: FunctionComponent<WorldBorderLayerProps> = ({ displayed }) => {
  // Any child elements of the react-leaflet MapContainer can access the Map instance
  // through the use of a custom hook.
  const mapCurrent = useMap();

  const layerReference = useRef<GeoJSONLeaflet | null>(null);

  useEffect(() => {
    if (layerReference.current != undefined) {
      if (displayed) {
        layerReference.current.addTo(mapCurrent);
      } else {
        layerReference.current.removeFrom(mapCurrent);
      }
    }
  }, [mapCurrent, displayed]);

  return (
    <GeoJSON
      ref={layerReference}
      // If the zoom level changes, the world border should reload.
      key={mapCurrent.getZoom()}
      style={{
        // fillPattern: worldBorderPattern,
        stroke: false,
        fillOpacity: 0.3,
        color: 'red',
      }}
      data={WorldBorderData}
    />
  );
}
Example #4
Source File: EditablePolyline.tsx    From project-tauntaun with GNU Lesser General Public License v3.0 6 votes vote down vote up
export function EditablePolylineNonMemo(props: EditablePolylineProps) {
  // https://github.com/bbecquet/Leaflet.PolylineDecorator
  const map = useMap();

  React.useEffect(() => {
    if (!map) {
      console.error('Map is undefined!');
      return;
    }

    return editablePolylineCtor(map, props);
  });

  return null;
}
Example #5
Source File: Ruler.tsx    From project-tauntaun with GNU Lesser General Public License v3.0 6 votes vote down vote up
export function Ruler() {
  const map = useMap();
  const mapCenter = map.getCenter();
  const mapBoundEast = map.getBounds().getEast();
  const mapBoundWest = map.getBounds().getWest();
  const quarter = Math.abs(mapBoundWest - mapBoundEast) / 4.0;
  const [positions, setPositions] = useState([
    new LatLng(mapCenter.lat, mapCenter.lng - quarter),
    new LatLng(mapCenter.lat, mapCenter.lng + quarter)
  ]);

  const handlePositionModified = (index: number, pos: LatLng) => {
    const newPositions = [...positions];
    newPositions[index] = pos;
    setPositions(newPositions);
  };

  return (
    <React.Fragment>
      <EditablePolyline
        positions={positions}
        color="black"
        stroke={true}
        weight={3}
        opacity={1}
        dashArray="1"
        drawMidmarkers={false}
        onPositionModified={handlePositionModified}
      />
      <DistanceMarkers positions={positions} showBearing={true} />
    </React.Fragment>
  );
}
Example #6
Source File: MapClusterMarker.tsx    From Teyvat.moe with GNU General Public License v3.0 5 votes vote down vote up
MapClusterMarker = forwardRef<leaflet.MarkerClusterGroup, MapClusterMarkerProps>(
  ({ children = null, clusterFunction = offClusterFunction }, reference) => {
    const map = useMap();

    const generateSpiderPoints = (
      _childMarkerCount: number,
      _centerPoint: leaflet.Point,
      childMarkers: leaflet.Marker[]
    ): leaflet.Point[] => {
      const result: leaflet.Point[] = [];

      result.length = childMarkers.length;

      for (let index = childMarkers.length - 1; index >= 0; index -= 1) {
        const childMarker = childMarkers[index];
        if (childMarker != null) {
          const childCenter = map.latLngToLayerPoint(childMarker.getLatLng());
          result[index] = leaflet.point(childCenter.x, childCenter.y);
        }
      }

      return result;
    };

    return (
      <MarkerClusterGroup
        ref={reference}
        disableClusteringAtZoom={8}
        iconCreateFunction={createClusterIcon}
        maxClusterRadius={clusterFunction}
        // Configure how the coverage line is displayed.
        polygonOptions={{
          color: '#008E8A',
          weight: 3,
          dashArray: '8',
          fillOpacity: 0.4,
        }}
        showCoverageOnHover
        singleMarkerMode={false}
        spiderfyOnEveryZoom // Spiderfy on click (all zoom levels)
        spiderfyShapePositions={generateSpiderPoints}
        zoomToBoundsOnClick={false}
        chunkedLoading // Split the addLayers processing in to small intervals so that the page does not freeze.
      >
        {children}
      </MarkerClusterGroup>
    );
  }
)
Example #7
Source File: MapContextMenu.tsx    From project-tauntaun with GNU Lesser General Public License v3.0 5 votes vote down vote up
export function MapContextMenu(props: MapContextMenuProps) {
  const { commanderMode, setShowAddFlightForm, setLocation } = AppStateContainer.useContainer();

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

  const { mission } = MissionStateContainer.useContainer();

  const map = useMap();

  const contextMenuOptionsAdmin: Array<ContextMenuOption> = [
    { label: 'Add Flight', value: 'add_flight' },
    { label: 'Add JTAC (Experimental)', value: 'addJTAC' }
  ];
  const contextMenuOptionsNormal: Array<ContextMenuOption> = [{ label: 'Recon', value: 'recon' }];
  const contextMenuOptions: Array<ContextMenuOption> = commanderMode
    ? [...contextMenuOptionsAdmin, ...contextMenuOptionsNormal]
    : contextMenuOptionsNormal;

  const addFlightOnClick = (position: ClickPosition) => {
    if (position.latlon) {
      setShowAddFlightForm(true);
      setLocation(position.latlon);
    }
  };

  const addJTACOnClick = (position: ClickPosition) => {
    if (position.latlon) {
      const country = Object.keys(mission.coalition[sessionCoalition].countries)[0];

      gameService.sendAddJTAC(sessionCoalition, country, position.latlon);
    }
  };

  const reconOnClick = (position: ClickPosition) => {
    if (position.latlon) {
      const kml = convertLeafletMapToKml(map);
      saveKmlFile('markers.kml', kml);
      openInNewTab(getGoogleEarthUrl(position.latlon));
    }
  };

  const handleOptionSelected = (value: string, position: ClickPosition) => {
    switch (value) {
      case 'add_flight':
        addFlightOnClick(position);
        break;
      case 'recon':
        reconOnClick(position);
        break;
      case 'addJTAC':
        addJTACOnClick(position);
        break;
    }
  };

  return <ContextMenu {...props} options={contextMenuOptions} onOptionSelected={handleOptionSelected} />;
}
Example #8
Source File: Maps.tsx    From roamjs-com with MIT License 4 votes vote down vote up
Markers = ({
  id,
  href,
  markers,
}: {
  id: string;
  href: string;
  markers: RoamMarker[];
}) => {
  const map = useMap();
  const mouseRef = useRef(null);
  const openMarker = (marker: LMarker) => () => {
    mouseRef.current = marker;
    marker.openPopup();
  };
  const closeMarker = (marker: LMarker) => () => {
    mouseRef.current = null;
    setTimeout(() => {
      if (mouseRef.current !== marker) {
        marker.closePopup();
      }
    }, 100);
  };
  useEffect(() => {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore until there's a better way to grab markers
    const leafletMarkers = map._layers as { [key: string]: LMarker };
    Object.keys(leafletMarkers).forEach((k) => {
      const m = leafletMarkers[k];
      m.on({
        mouseover: openMarker(m),
        mouseout: closeMarker(m),
        click: (e) => {
          const extractedTag = extractTag(m.options.title);
          const pageUid = getPageUidByPageTitle(extractedTag);
          if (pageUid) {
            if (e.originalEvent.shiftKey) {
              openBlockInSidebar(pageUid);
            } else {
              window.roamAlphaAPI.ui.mainWindow.openPage({
                page: { uid: pageUid },
              });
            }
          }
        },
      });
    });
    const observer = new MutationObserver((mrs) => {
      mrs
        .flatMap((mr) => Array.from(mr.addedNodes))
        .filter((n) => n.nodeName === "DIV")
        .map((n) => n as HTMLDivElement)
        .map((n) =>
          n.classList.contains("leaflet-popup")
            ? n
            : n.getElementsByClassName("leaflet-popup")[0]
        )
        .filter((n) => !!n)
        .forEach((n) => {
          const marker = Object.values(leafletMarkers).find(
            (m) =>
              n
                .querySelector(".roamjs-marker-data")
                .getAttribute("data-uid") === m.options.title
          );
          n.addEventListener("mouseenter", openMarker(marker));
          n.addEventListener("mouseleave", closeMarker(marker));
        });
      mrs
        .flatMap((mr) => Array.from(mr.addedNodes))
        .map((n) =>
          n.parentElement.querySelector<HTMLAnchorElement>(".rm-alias")
        )
        .filter((n) => !!n)
        .forEach((anchor) => {
          renderAlias({
            p: anchor,
            children: anchor.innerText,
            blockUid: anchor.href.match(/\/page\/(.*)/)?.[1] || "",
          });
        });
    });
    observer.observe(document.getElementById(id), {
      childList: true,
      subtree: true,
    });
    return () => observer.disconnect();
  });
  return (
    <>
      {markers.map((m, i) => (
        <Marker
          position={[m.x, m.y]}
          icon={MarkerIcon}
          key={i}
          title={m.uid}
          riseOnHover
        >
          <Popup>
            <div
              className={"roamjs-marker-data roamjs-block-view"}
              id={`roamjs-map-marker-${m.uid}`}
              data-uid={m.uid}
              style={{ display: "flex" }}
              dangerouslySetInnerHTML={{
                __html: parseRoamMarked(m.tag),
              }}
            />
          </Popup>
        </Marker>
      ))}
    </>
  );
}