leaflet#LatLngTuple TypeScript Examples

The following examples show how to use leaflet#LatLngTuple. 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: Marker.tsx    From metro-fare with MIT License 6 votes vote down vote up
FromToMarker = ({
  position,
  type,
}: {
  position: LatLngTuple;
  type: "from" | "to";
}) => {
  const classes = useStyle();
  const color = type === "from" ? classes.blue : classes.red;
  const fromIcon = divIcon({
    className: `fas fa-map-marker-alt ${classes.markerLayout} ${color}`,
  });
  return <Marker position={position} icon={fromIcon} />;
}
Example #2
Source File: MetroMap.tsx    From metro-fare with MIT License 6 votes vote down vote up
MetroMap = () => {
  const [mapCenter, setMapCenter] = useState<LatLngTuple>(DEFAULT_MAP_CENTER);
  const { setShowMetroLayers } = useMapContext();
  const { trip, journey } = useTripContext();

  useEffect(() => {
    if (
      !(
        mapCenter[0] === DEFAULT_MAP_CENTER[0] &&
        mapCenter[1] === DEFAULT_MAP_CENTER[1]
      )
    ) {
      setMapCenter(DEFAULT_MAP_CENTER);
    }
  }, [mapCenter]);

  useEffect(() => {
    const isVisible = journey.route.length === 0;
    setShowMetroLayers({
      mrtBlue: isVisible,
      btsSilom: isVisible,
      btsSukhumvit: isVisible,
      btsGold: isVisible,
      arl: isVisible,
      brt: isVisible,
    });
  }, [journey, setShowMetroLayers]);

  return (
    <div className="width-100 height-100">
      <Map
        className="width-100 height-100"
        center={mapCenter}
        zoom={12}
        minZoom={12}
        maxZoom={17}
        zoomControl={false}
      >
        <MapControl />
        <TileLayer
          attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        <MetroLineLayers />
        {journey.route.length > 0 && <TravelRouteLayer />}
        <FromToStationLayer trip={trip} />
      </Map>
    </div>
  );
}
Example #3
Source File: util.service.ts    From metro-fare with MIT License 6 votes vote down vote up
getPolyLineFromStations = (stations: Station[]): LatLngTuple[] => {
    return stations.map(station => station.position);
}
Example #4
Source File: mapConstants.ts    From metro-fare with MIT License 5 votes vote down vote up
DEFAULT_MAP_CENTER: LatLngTuple = [13.773565, 100.521852]
Example #5
Source File: mapConstants.ts    From metro-fare with MIT License 5 votes vote down vote up
DUMMY_MAP_POSITION: LatLngTuple = [13.773565, 100.521853]
Example #6
Source File: OverviewSection.tsx    From po8klasie with GNU General Public License v3.0 5 votes vote down vote up
OverviewSection: FC<SectionComponentProps> = ({ school }) => {
  const position: LatLngTuple = parseCoords(school);

  return (
    <SchoolInfoSection id="overview" updateTime={school.updatedAt}>
      <div className="py-3 px-5">
        <div className="grid lg:grid-cols-6">
          <div className="col-span-3 xl:col-span-2">
            <h3 className="text-lg font-bold text-dark">Podstawowe informacje</h3>
            <ul className="mt-2 text-gray">
              <li className="my-2">
                <ItemWithIcon icon={MdOutlineHome}>
                  {school.street} {school.buildingNo}, {school.zipCode} {school.town}
                </ItemWithIcon>
              </li>
              <li className="my-2">
                <ItemWithIcon icon={MdLink}>{school.website}</ItemWithIcon>
              </li>
              {/* not yet implemented */}
              {/* <li className="my-2"> */}
              {/*   <ItemWithIcon icon={MdPhone}>{school.}</ItemWithIcon> */}
              {/* </li> */}
              <li className="my-2">
                <ItemWithIcon icon={MdOutlineEmail}>{school.email}</ItemWithIcon>
              </li>
              {/* not yet implemented */}
              {/* <li className="my-2"> */}
              {/*   <ItemWithIcon icon={MdOutlineSchool}>{school.}</ItemWithIcon> */}
              {/* </li> */}
            </ul>
          </div>
          <div className="col-span-3 xl:col-span-4 h-72 xl:mt-0 mt-2">
            <SchoolLocationMap position={position} />
          </div>
        </div>
      </div>
      {school.description && (
        <div className="border-t border-light py-2 px-5">
          <h4 className="text-dark text-base font-semibold">O szkole</h4>
          <p className="text-gray my-2">{school.description}</p>
        </div>
      )}
    </SchoolInfoSection>
  );
}
Example #7
Source File: map.ts    From po8klasie with GNU General Public License v3.0 5 votes vote down vote up
parseCoords = (school: RailsApiSchool): LatLngTuple => [
  parseFloat(school.latitude),
  parseFloat(school.longitude),
]
Example #8
Source File: index.tsx    From aqualink-app with MIT License 4 votes vote down vote up
SiteMap = ({
  siteId,
  spotterPosition,
  polygon,
  surveyPoints,
  selectedPointId,
  surveyPointEditModeEnabled,
  editPointLatitude,
  editPointLongitude,
  onEditPointCoordinatesChange,
  classes,
}: SiteMapProps) => {
  const dispatch = useDispatch();
  const mapRef = useRef<Map>(null);
  const markerRef = useRef<Marker>(null);
  const editPointMarkerRer = useRef<Marker>(null);
  const draftSite = useSelector(siteDraftSelector);
  const user = useSelector(userInfoSelector);
  const [focusedPoint, setFocusedPoint] = useState<SurveyPoints>();

  const reverseCoords = (coordArray: Position[]): [Position[]] => {
    return [coordArray.map((coords) => [coords[1], coords[0]])];
  };

  const selectedSurveyPoint = surveyPoints.find(
    (item) => item.id === selectedPointId
  );

  const setCenter = (
    inputMap: L.Map,
    latLng: [number, number],
    zoom: number
  ) => {
    const maxZoom = Math.max(inputMap.getZoom() || 15, zoom);
    const pointBounds = L.latLngBounds(latLng, latLng);
    inputMap.flyToBounds(pointBounds, {
      maxZoom,
      duration: 2,
      paddingTopLeft: L.point(0, 200),
    });
  };

  // Fit the polygon constructed by the site's center and its survey points
  const fitSurveyPointsPolygon = useCallback(
    (inputMap: L.Map, siteCenter: Point) => {
      inputMap.fitBounds(
        L.polygon([
          [siteCenter.coordinates[1], siteCenter.coordinates[0]],
          ...surveyPoints
            .filter((item) => item.polygon?.type === "Point")
            .map((item) => {
              const coords = item.polygon?.coordinates as Position;
              // Reverse coordinates since they come as [lng, lat]
              return [coords[1], coords[0]] as LatLngTuple;
            }),
        ]).getBounds()
      );
    },
    [surveyPoints]
  );

  useEffect(() => {
    if (
      mapRef?.current?.leafletElement &&
      focusedPoint?.polygon?.type === "Point"
    ) {
      const [lng, lat] = focusedPoint.polygon.coordinates;
      setCenter(mapRef.current.leafletElement, [lat, lng], 15);
    }
  }, [focusedPoint]);

  useEffect(() => {
    const { current } = mapRef;
    if (current?.leafletElement) {
      const map = current.leafletElement;
      // Initialize map's position to fit the given polygon
      if (polygon.type === "Polygon") {
        map.fitBounds(L.polygon(polygon.coordinates).getBounds());
      } else if (draftSite?.coordinates) {
        map.panTo(
          new L.LatLng(
            draftSite.coordinates.latitude || polygon.coordinates[1],
            draftSite.coordinates.longitude || polygon.coordinates[0]
          )
        );
      } else if (some(surveyPoints, (item) => item.polygon?.type === "Point")) {
        fitSurveyPointsPolygon(map, polygon);
      } else {
        map.panTo(new L.LatLng(polygon.coordinates[1], polygon.coordinates[0]));
      }
    }
  }, [draftSite, fitSurveyPointsPolygon, polygon, surveyPoints]);

  const handleDragChange = () => {
    const { current } = markerRef;
    if (current?.leafletElement) {
      const mapMarker = current.leafletElement;
      const { lat, lng } = mapMarker.getLatLng().wrap();
      dispatch(
        setSiteDraft({
          coordinates: {
            latitude: lat,
            longitude: lng,
          },
        })
      );
    }
  };

  const handleEditPointDragChange = () => {
    const { current } = editPointMarkerRer;
    if (current && current.leafletElement && onEditPointCoordinatesChange) {
      const mapMarker = current.leafletElement;
      const { lat, lng } = mapMarker.getLatLng().wrap();
      onEditPointCoordinatesChange(lat.toString(), lng.toString());
    }
  };

  return (
    <Map
      ref={mapRef}
      minZoom={1}
      maxZoom={17}
      zoom={13}
      dragging
      scrollWheelZoom={false}
      className={classes.map}
      tap={false}
      maxBoundsViscosity={1.0}
      maxBounds={mapConstants.MAX_BOUNDS}
    >
      <TileLayer url="https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}" />
      {polygon.type === "Polygon" ? (
        <Polygon positions={reverseCoords(...polygon.coordinates)} />
      ) : (
        <>
          {/* Marker to listen to survey point drag changes on edit mode */}
          {surveyPointEditModeEnabled && (
            <Marker
              ref={editPointMarkerRer}
              draggable={surveyPointEditModeEnabled}
              ondragend={handleEditPointDragChange}
              icon={surveyPointIcon(true)}
              zIndexOffset={100}
              position={[
                editPointLatitude ||
                  (selectedSurveyPoint?.polygon?.type === "Point" &&
                    selectedSurveyPoint.polygon.coordinates[1]) ||
                  polygon.coordinates[1],
                editPointLongitude ||
                  (selectedSurveyPoint?.polygon?.type === "Point" &&
                    selectedSurveyPoint.polygon.coordinates[0]) ||
                  polygon.coordinates[0],
              ]}
            />
          )}
          <Marker
            ref={markerRef}
            draggable={Boolean(draftSite)}
            ondragend={handleDragChange}
            icon={pinIcon}
            position={[
              draftSite?.coordinates?.latitude || polygon.coordinates[1],
              draftSite?.coordinates?.longitude || polygon.coordinates[0],
            ]}
          />
          {surveyPoints.map(
            (point) =>
              point?.polygon?.type === "Point" &&
              !samePosition(polygon, point.polygon) &&
              (point.id !== selectedPointId || !surveyPointEditModeEnabled) && ( // Hide selected survey point marker if it is in edit mode
                <Marker
                  key={point.id}
                  icon={surveyPointIcon(point.id === selectedPointId)}
                  position={[
                    point.polygon.coordinates[1],
                    point.polygon.coordinates[0],
                  ]}
                  onclick={() => setFocusedPoint(point)}
                >
                  <SurveyPointPopup siteId={siteId} point={point} />
                </Marker>
              )
          )}
        </>
      )}
      {!draftSite && spotterPosition && isManager(user) && (
        <Marker
          icon={buoyIcon}
          position={[
            spotterPosition.latitude.value,
            spotterPosition.longitude.value,
          ]}
        />
      )}
    </Map>
  );
}
Example #9
Source File: index.tsx    From aqualink-app with MIT License 4 votes vote down vote up
Popup = ({ site, classes, autoOpen }: PopupProps) => {
  const { map } = useLeaflet();
  const siteOnMap = useSelector(siteOnMapSelector);
  const popupRef = useRef<LeafletPopup>(null);
  const { name, region } = getSiteNameAndRegion(site);
  const isNameLong = name?.length && name.length > maxLengths.SITE_NAME_POPUP;

  const { dhw, satelliteTemperature } = site.collectionData || {};

  const onExploreButtonClick = () => {
    trackButtonClick(
      GaCategory.BUTTON_CLICK,
      GaAction.MAP_PAGE_BUTTON_CLICK,
      "Explore"
    );
  };

  useEffect(() => {
    if (
      map &&
      popupRef?.current &&
      siteOnMap?.id === site.id &&
      siteOnMap?.polygon.type === "Point" &&
      autoOpen
    ) {
      const { leafletElement: popup } = popupRef.current;
      const [lng, lat] = siteOnMap.polygon.coordinates;

      const point: LatLngTuple = [lat, lng];
      popup.setLatLng(point).openOn(map);
    }
  }, [autoOpen, map, site.id, siteOnMap]);

  return (
    <LeafletPopup
      ref={siteOnMap?.id === site.id ? popupRef : null}
      closeButton={false}
      className={classes.popup}
      autoPan={false}
    >
      <Card>
        <CardHeader
          className={classes.popupHeader}
          classes={{
            content: classes.popupHeaderContent,
            subheader: classes.subheader,
          }}
          title={
            <span title={isNameLong && name ? name : undefined}>
              {isNameLong
                ? `${name?.substring(0, maxLengths.SITE_NAME_POPUP)}...`
                : name}
            </span>
          }
          subheader={region}
        />
        <CardContent>
          <Grid container item xs={12}>
            <Grid item xs={6}>
              <Grid container item xs={12}>
                <Typography variant="caption" color="textSecondary">
                  SST
                </Typography>
              </Grid>
              <Grid container item xs={12}>
                <Typography
                  style={{ color: colors.lightBlue }}
                  variant="h5"
                  color="textSecondary"
                >
                  {`${formatNumber(satelliteTemperature, 1)}  °C`}
                </Typography>
              </Grid>
            </Grid>
            <Grid item xs={6}>
              <Grid container item xs={12}>
                <Typography variant="caption" color="textSecondary">
                  HEAT STRESS
                </Typography>
              </Grid>
              <Grid container alignItems="flex-end" item xs={12}>
                <Typography
                  style={{
                    color: `${dhwColorFinder(dhw)}`,
                  }}
                  variant="h5"
                  color="textSecondary"
                >
                  {formatNumber(dhw, 1)}
                  &nbsp;
                </Typography>
                <Tooltip title="Degree Heating Weeks - a measure of the amount of time above the 20 year historical maximum temperatures">
                  <Typography
                    style={{
                      color: `${dhwColorFinder(dhw)}`,
                      position: "relative",
                      bottom: 0,
                    }}
                    variant="h6"
                    color="textSecondary"
                  >
                    DHW
                  </Typography>
                </Tooltip>
              </Grid>
            </Grid>
          </Grid>
          <Grid style={{ margin: "1rem 0 1rem 0" }} container item xs={12}>
            <Grid item>
              <Link
                style={{ color: "inherit", textDecoration: "none" }}
                to={`/sites/${site.id}`}
              >
                <Button
                  onClick={onExploreButtonClick}
                  size="small"
                  variant="outlined"
                  color="primary"
                >
                  EXPLORE
                </Button>
              </Link>
            </Grid>
          </Grid>
        </CardContent>
      </Card>
    </LeafletPopup>
  );
}