leaflet#CRS TypeScript Examples

The following examples show how to use leaflet#CRS. 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: map.component.ts    From dayz-server-manager with MIT License 6 votes vote down vote up
private async setUpWorld(name: string): Promise<void> {

        this.mapName = name;
        const urlBase = `${this.mapHost}/${this.mapName}`;
        this.info = (await this.http.get(
            `${urlBase}/data.json`,
        ).toPromise()) as MapInfo;
        this.mapScale = Math.ceil(
            Math.log(
                this.info!.worldSize / ((this.info!.tileSize ?? 256) / (this.info!.scale ?? 1)),
            ) / Math.log(2),
        );

        this.options = {
            layers: [],
            zoom: this.info.defaultZoom ?? (this.info.minZoom ?? 1),
            center: [0, 0],
            minZoom: this.info.minZoom ?? 1,
            maxZoom: this.info.maxZoom ?? 7,
            crs: CRS.Simple,
        };

        console.log('Map Setup Done');
    }
Example #2
Source File: LeafletMap.tsx    From Teyvat.moe with GNU General Public License v3.0 4 votes vote down vote up
LeafletMap: FunctionComponent = () => {
  const classes = useStyles();

  const onTileLayerLoadStart = useCallback(() => {
    dispatchSetLoading('loadLeafletTiles', 'progress');
  }, []);

  const onTileLayerLoadError = useCallback(() => {
    dispatchSetLoading('loadLeafletTiles', 'error');
  }, []);

  const onTileLayerLoadSuccess = useCallback(() => {
    dispatchSetLoading('loadLeafletTiles', true);
  }, []);

  return (
    <MapContainer
      className={classes.main}
      maxBounds={MAP_BOUNDS}
      center={MAP_CENTER}
      zoom={DEFAULT_ZOOM}
      zoomDelta={0.5}
      editable
      crs={CRS.Simple}
      zoomSnap={0.5}
      maxZoom={MAXIMUM_ZOOM}
      minZoom={MINIMUM_ZOOM}
      attributionControl={false} // Override the Leaflet attribution with our own AttributionControl.
      zoomControl={false}
    >
      {/* Handles events related to the map position. */}
      <MapPositionHandler />
      {/* Handles events related to the map editing, and renders the editor controls.. */}
      <MapEditorHandler />
      {/* Controls the actual map image. */}
      <TileLayer
        onLoadSuccess={onTileLayerLoadSuccess}
        onLoadStart={onTileLayerLoadStart}
        onLoadError={onTileLayerLoadError}
      />

      <RegionLabelLayer />
      {/* <WorldBorderLayer /> */}
      <EditorLayer />

      {/* Controls the zoom buttons in the top left corner. */}
      <ZoomControl zoomInTitle="+" zoomOutTitle="-" />
      <DebugControls />

      {/* Display each visible feature. */}
      {_.map(getMapFeatureKeys(), (key) => {
        const feature = getMapFeature(key);
        if (!feature) {
          console.error(`ERROR: Feature '${key}' is not defined.`);
          return null;
        }

        return (
          <ErrorHandler key={`feature:${key}`} errorHandler={ErrorLayer}>
            <FeatureLayer mapFeature={feature} featureKey={key} />
          </ErrorHandler>
        );
      })}

      {/* Display each visible route. */}
      {_.map(getMapRouteGroupKeys(), (key) => {
        const route = getMapRouteGroup(key);
        if (!route) {
          console.error(`ERROR: Route '${key}' is not defined.`);
          return null;
        }

        return (
          <ErrorHandler key={`route:${key}`} errorHandler={ErrorLayer}>
            <RouteLayer routeKey={key} routeGroup={route} />
          </ErrorHandler>
        );
      })}
    </MapContainer>
  );
}
Example #3
Source File: rendering.ts    From squadlanes with GNU Affero General Public License v3.0 4 votes vote down vote up
export function resetMap(layerData: LayerData) {
  // remove existing map data
  if (map !== null) {
    map.remove();
    renderInfos = new Map();
    capturePointByCircleMarker = new Map();
    circleMarkerByCapturePoint = new Map();
  }

  const bounds = layerData.background.corners;

  const baseBounds = [
    [bounds[0].y, bounds[0].x],
    [bounds[1].y, bounds[1].x],
  ];
  const width = Math.abs(bounds[0].x - bounds[1].x);
  const height = Math.abs(bounds[0].y - bounds[1].y);

  const up_left_x = Math.min(bounds[0].x, bounds[1].x);
  const up_left_y = Math.min(bounds[0].y, bounds[1].y);

  const zoomOffset = 0;
  let tileSize = 256;

  const x_stretch = tileSize / width;
  const y_stretch = tileSize / height;

  const crs = extend({}, CRS.Simple, {
    // Move origin to upper left corner of map
    // need to do this because TileLayer always puts the left-upper corner on the origin
    transformation: new Transformation(
      x_stretch,
      -up_left_x * x_stretch,
      y_stretch,
      -up_left_y * y_stretch
    ),
  });

  map = leafletMap("map", {
    crs: crs,
    minZoom: 0,
    maxZoom: 6,
    zoomSnap: 0.1,
    zoomDelta: 1.0,
    dragging: true,
    boxZoom: true,
    scrollWheelZoom: true,
    touchZoom: true,
    zoomControl: true,
    doubleClickZoom: false,
    attributionControl: false,
  });

  // @ts-ignore
  map.fitBounds(baseBounds);
  map.createPane("cp");
  map.getPane("cp")!.style.zIndex = "20";
  map.createPane("cpTooltip");
  map.getPane("cpTooltip")!.style.zIndex = "30";
  map.createPane("confirmationLines");
  map.getPane("confirmationLines")!.style.zIndex = "10";
  map.createPane("background");
  map.getPane("background")!.style.zIndex = "0";

  new TileLayer(
    `map-tiles/${layerData.background.minimap_filename}/{z}/{x}/{y}.png`,
    {
      tms: false,
      maxNativeZoom: 4,
      zoomOffset: zoomOffset,
      // scale tiles to match minimap width and height
      tileSize: tileSize,
      pane: "background",
      // @ts-ignore
      bounds: baseBounds,
    }
  ).addTo(map);

  // create markers for capture points
  mapData.capturePoints.forEach((cp) => {
    const cm = circleMarker(cp.pos, {
      radius: 20,
      pane: "cp",
    });

    // remember mapping between CircleMarker and CapturePoint
    circleMarkerByCapturePoint.set(cp, cm);
    capturePointByCircleMarker.set(cm, cp);

    // during mouseover, the font color and size changes
    // (we add a CSS class and re-open the tooltip)
    cm.on("mouseover", (ev) => {
      const tt = cm.getTooltip();
      if (tt !== undefined) {
        // this will probably break at some point
        // @ts-ignore
        DomUtil.addClass(tt._container, "mouseover");
      }
      // re-open tooltip to make sure text is still centered
      cm.closeTooltip();
      cm.openTooltip();
    });
    cm.on("mouseout", (ev) => {
      const tt = cm.getTooltip();
      if (tt !== undefined) {
        // @ts-ignore
        L.DomUtil.removeClass(tt._container, "mouseover");
      }
      cm.closeTooltip();
      cm.openTooltip();
    });
  });

  // make sure the leaflet map rescales properly when the window is resized
  const mapDiv = document.getElementById("map")!;
  new ResizeObserver(() => {
    map!.invalidateSize();
    // @ts-ignore
    map!.fitBounds(baseBounds, {
      animate: false,
    });
  }).observe(mapDiv);

  // Debug
  if (window.location.hostname.startsWith("dev.")) {
    map.addEventListener("mousedown", function (ev) {
      // @ts-ignore
      const lat = ev.latlng.lat;
      // @ts-ignore
      const lng = ev.latlng.lng;
    });
  }
}