react-leaflet#FeatureGroup TypeScript Examples

The following examples show how to use react-leaflet#FeatureGroup. 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: MetroMap.tsx    From metro-fare with MIT License 6 votes vote down vote up
FromToStationLayer = ({ trip }: { trip: Trip }) => {
  const fromStation = getStation(trip.fromId);
  const toStation = getStation(trip.toId);
  // TODO: add popover to show station name and unselect option
  return (
    <FeatureGroup name="from-to-station">
      {fromStation && (
        <FromToMarker position={fromStation.position} type={"from"} />
      )}
      {toStation && <FromToMarker position={toStation.position} type={"to"} />}
    </FeatureGroup>
  );
}
Example #2
Source File: TravelRouteLayer.tsx    From metro-fare with MIT License 5 votes vote down vote up
TravelRouteLayer = () => {
  const { journey } = useContext(TripContext);

  const from = getStation(journey.from);
  const to = getStation(journey.to);

  if (!(from && to)) {
    return null;
  }
  const stationIds = getStationIdsFromJourney(journey);
  const allStationsInRoute = getAllStations(stationIds);

  const intermediateStations = allStationsInRoute.filter(
    (station) => station.id !== from.id && station.id !== to.id
  );

  return (
    <>
      <FeatureGroup name="travel-route">
        {allStationsInRoute.map((currentStation, index) => {
          if (index === 0) return null;
          const prevStation = allStationsInRoute[index - 1];
          const polyline = [prevStation.position, currentStation.position];
          const color = getInterChangeLineColor(
            currentStation.lineType,
            prevStation.lineType
          );

          return (
            <Polyline
              key={`travel-route-${prevStation.id}-${currentStation.id}`}
              positions={polyline}
              color={color}
              weight={7}
            />
          );
        })}
      </FeatureGroup>
      <FeatureGroup name="travel-route-station">
        <StationMarker
          station={from as Station}
          fillColor={colors.fromStation}
          showPopup={false}
          radius={12}
        />
        {intermediateStations.map((station) => {
          return (
            <StationMarker
              key={`intermediate-${station.id}`}
              station={station as Station}
              fillColor={getColorFromLineType(station.lineType)}
              showPopup={false}
              radius={12}
            />
          );
        })}
        <StationMarker
          station={to as Station}
          fillColor={colors.toStation}
          showPopup={false}
          radius={12}
        />
      </FeatureGroup>
    </>
  );
}
Example #3
Source File: Map.tsx    From covid19map with MIT License 4 votes vote down vote up
Map = ({
  center,
  zoom,
  markers = [],
  clusters = {},
  onMarkerClick,
  maxCases,
  outerBounds,
  innerBounds,
  location
}: {
  center: any;
  zoom: number;
  markers: any[];
  clusters: any;
  onMarkerClick: any;
  maxCases: number;
  outerBounds: any;
  innerBounds: any;
  location: any;
}) => {
  const theme = useTheme();
  const mapRef = useRef<any>(null);
  const [currentLocation, setCurrentLocation] = useState<string>();
  const [currentZoom, setCurrentZoom] = useState(100);

  useEffect(() => {
    mapRef?.current?.leafletElement.fitBounds(innerBounds);
  }, [mapRef.current]);

  useEffect(() => {
    mapRef?.current?.leafletElement.closePopup();
    setCurrentLocation('');
  }, [location]);

  const getRegionIcon = (
    className: string,
    totalCases: number,
    name: string
  ) => {
    const iconSize = 24;
    return L.divIcon({
      className: `marker ${className}`,
      iconSize: [iconSize, iconSize],
      html: `<div>${
        name === 'Managed Isolation' ? 'MIQ: ' : ''
      }${totalCases}</div>`
    });
  };

  const getClusterIcon = (className: string, totalCases: number) => {
    const normalise = totalCases / 100;
    const iconSize = 24 + normalise * 15;
    return L.divIcon({
      className: `marker ${className}`,
      iconSize: [iconSize, iconSize],
      html: `<div></div>`
    });
  };

  const onLocationClick = (name: string) => {
    setCurrentLocation(name);
    onMarkerClick(name);
  };

  const onZoomend = () => {
    if (mapRef.current) {
      setCurrentZoom(mapRef.current?.leafletElement.getZoom());
    }
  };

  return (
    <div style={{ position: 'relative' }}>
      <LeafletMap
        // onClick={() => onLocationClick('')}
        ref={mapRef}
        maxBounds={outerBounds}
        center={center}
        zoom={zoom}
        maxZoom={7}
        minZoom={5}
        zoomControl={true}
        doubleClickZoom={true}
        scrollWheelZoom={true}
        dragging={true}
        animate={true}
        easeLinearity={0.35}
        onZoomend={onZoomend}
      >
        <TileLayer
          url="//{s}.basemaps.cartocdn.com/rastertiles/voyager_nolabels/{z}/{x}/{y}{r}.png"
          attribution='&copy; <a href="//www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>'
        />
        {markers.map(
          (
            {
              name,
              latlng,
              boundary,
              totalCases,
              active,
              recovered,
              deaths,
              inHospital,
              level
            },
            i
          ) => (
            <>
              {latlng && (
                <FeatureGroup key={i}>
                  <Marker
                    position={latlng}
                    icon={getRegionIcon(
                      `region ${inHospital > 0 ? 'hospital' : ''}`,
                      active,
                      name
                    )}
                    zIndexOffset={100}
                    // onClick={() => {
                    //   onLocationClick(name);
                    //   gtag.event('Marker', 'Map', name);
                    // }}
                  />
                  <Popup>
                    <StyledPopup>
                      <div className="location">{name}</div>
                      <div className="cases">
                        {active} active case{active > 1 && 's'}
                        <br />
                        {recovered} recovered
                        <br />
                        {totalCases} total case{totalCases > 1 && 's'}
                        {deaths > 0 && (
                          <>
                            <br />
                            {deaths} death{deaths > 1 && 's'}
                          </>
                        )}
                      </div>
                      {inHospital > 0 && (
                        <div className="cases">{inHospital} in hospital</div>
                      )}
                    </StyledPopup>
                  </Popup>
                  {boundary && (
                    <Polygon
                      color={currentLocation === name ? 'white' : 'black'}
                      opacity={currentLocation === name ? 1 : 0.2}
                      weight={currentLocation === name ? 3 : 1}
                      fillColor={theme[alertColours[level - 1]]}
                      // fillOpacity={((active || 0) - -10) / (maxCases + 10 - 1)}
                      // fillOpacity={(level - 1) / (4 - 1)}
                      fillOpacity={0.8}
                      positions={boundary[0]}
                      // smoothFactor={10}
                      // onClick={() => {
                      //   onLocationClick(name);
                      //   gtag.event('Region', 'Map', name);
                      // }}
                    />
                  )}
                </FeatureGroup>
              )}
            </>
          )
        )}
        {Object.keys(clusters).map((regionName: string, j: number) =>
          Object.keys(clusters[regionName]).map(
            (clustLocName: string, k: number) => {
              const { latlng, count, items } = clusters[regionName][
                clustLocName
              ];

              return items.filter((x: any) => x.ongoing === 'Yes').length >
                0 ? (
                <Marker
                  key={k}
                  position={latlng}
                  icon={getClusterIcon('cluster', count)}
                  // onClick={() => gtag.event('Cluster', 'Map', clustLocName)}
                >
                  <Popup>
                    <StyledPopup>
                      <div className="head">
                        {clustLocName} cluster{items.length > 1 && 's'}
                      </div>
                      {items
                        .filter((x: any) => x.ongoing === 'Yes')
                        .map(
                          (
                            {
                              name,
                              totalCases
                            }: { name: string; totalCases: number },
                            l: number
                          ) => (
                            <div className="cluster-desc" key={l}>
                              <div className="location">{name}</div>
                              <div className="cases">{totalCases} cases</div>
                            </div>
                          )
                        )}
                    </StyledPopup>
                  </Popup>
                </Marker>
              ) : (
                <div key={k} />
              );
            }
          )
        )}
      </LeafletMap>
      <Styles currentZoom={currentZoom} />
    </div>
  );
}
Example #4
Source File: MetroLineLayers.tsx    From metro-fare with MIT License 4 votes vote down vote up
MetroLineLayers = () => {
  const { showMetroLineLayers } = useContext(MapContext);
  const mrtThapraPosition = MRT_BLUE[31].position;
  const polylineLayers = [
    {
      layername: "MRT-blue-line",
      color: colors.mrtBlue,
      polyline: [mrtThapraPosition, ...getPolyLineFromStations(MRT_BLUE)],
      isVisible: true,
    },
    {
      layername: "BTS-silom-line",
      color: colors.btsSilom,
      polyline: getPolyLineFromStations(BTS_SILOM),
      isVisible: true,
    },
    {
      layername: "BTS-sukhumvit-line",
      color: colors.btsSukhumvit,
      polyline: getPolyLineFromStations(BTS_SUKHUMVIT),
      isVisible: true,
    },
    {
      layername: "BTS-gold-line",
      color: colors.btsGold,
      polyline: getPolyLineFromStations(BTS_GOLD),
      isVisible: true,
    },
    {
      layername: "ARL-line",
      color: colors.arl,
      polyline: getPolyLineFromStations(ARL),
      isVisible: true,
    },
    {
      layername: "BRT-line",
      color: colors.brt,
      polyline: getPolyLineFromStations(BRT),
      isVisible: true,
    },
  ];
  const stationLayers = [
    {
      layername: "MRT-blue-station",
      isVisible: showMetroLineLayers.mrtBlue,
      color: colors.mrtBlue,
      stations: MRT_BLUE,
    },
    {
      layername: "BTS-silom-station",
      isVisible: showMetroLineLayers.btsSilom,
      color: colors.btsSilom,
      stations: BTS_SILOM,
    },
    {
      layername: "BTS-sukhumvit-station",
      isVisible: showMetroLineLayers.btsSukhumvit,
      color: colors.btsSukhumvit,
      stations: BTS_SUKHUMVIT,
    },
    {
      layername: "BTS-gold-station",
      isVisible: showMetroLineLayers.btsGold,
      color: colors.btsGold,
      stations: BTS_GOLD,
    },
    {
      layername: "ARL-station",
      isVisible: showMetroLineLayers.arl,
      color: colors.arl,
      stations: ARL,
    },
    {
      layername: "BRT-station",
      isVisible: showMetroLineLayers.brt,
      color: colors.brt,
      stations: BRT,
    },
  ];

  const displayPolylineLayers = () => {
    return polylineLayers.map((polylineLayer) => (
      <LayersControl.Overlay
        key={polylineLayer.layername}
        name={polylineLayer.layername}
        checked={polylineLayer.isVisible}
      >
        <FeatureGroup name={polylineLayer.layername}>
          <Polyline
            positions={polylineLayer.polyline}
            color={polylineLayer.color}
          />
        </FeatureGroup>
      </LayersControl.Overlay>
    ));
  };

  const displayStationLayers = () => {
    return stationLayers.map((stationLayer) => (
      <LayersControl.Overlay
        key={stationLayer.layername}
        name={stationLayer.layername}
        checked={stationLayer.isVisible}
      >
        <FeatureGroup name="mrt-blue-station">
          {stationLayer.stations.map((station) => (
            <StationMarker
              key={station.id}
              station={station}
              fillColor={stationLayer.color}
            />
          ))}
        </FeatureGroup>
      </LayersControl.Overlay>
    ));
  };

  return (
    <LayersControl position="topright">
      {displayPolylineLayers()}
      {displayStationLayers()}
    </LayersControl>
  );
}