Solve the scroll bar issue

This commit is contained in:
Alireza Adli 2023-11-10 16:44:21 -05:00
parent c451e572c8
commit b746aabeba
7 changed files with 375 additions and 441 deletions

View File

@ -8,7 +8,7 @@ const Sidebar: React.FC<{}> = (props) => {
return ( return (
<Fragment> <Fragment>
<div style={{ position: "static" }} id="sidebar" className={"info-container " + (collapsed? "offscreen": "")}> <div id="sidebar" className={"info-container " + (collapsed? "offscreen": "")}>
<button className="info-container-collapse btn btn-light" <button className="info-container-collapse btn btn-light"
onClick={() => setCollapsed(!collapsed)} onClick={() => setCollapsed(!collapsed)}
> >

View File

@ -1,33 +1,28 @@
import React, { useCallback, useEffect, useMemo, useState } from "react"; import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { Redirect, Route, Switch } from "react-router-dom"; import { Redirect, Route, Switch } from 'react-router-dom';
import loadable from "@loadable/component"; import loadable from '@loadable/component';
import { useRevisionId } from "./api-data/use-revision"; import { useRevisionId } from './api-data/use-revision';
import { useBuildingData } from "./api-data/use-building-data"; import { useBuildingData } from './api-data/use-building-data';
import { useUserVerifiedData } from "./api-data/use-user-verified-data"; import { useUserVerifiedData } from './api-data/use-user-verified-data';
import { useUrlBuildingParam } from "./nav/use-url-building-param"; import { useUrlBuildingParam } from './nav/use-url-building-param';
import { useUrlCategoryParam } from "./nav/use-url-category-param"; import { useUrlCategoryParam } from './nav/use-url-category-param';
import { useUrlModeParam } from "./nav/use-url-mode-param"; import { useUrlModeParam } from './nav/use-url-mode-param';
import BuildingView from "./building/building-view"; import BuildingView from './building/building-view';
import Categories from "./building/categories"; import Categories from './building/categories';
import { EditHistory } from "./building/edit-history/edit-history"; import { EditHistory } from './building/edit-history/edit-history';
import MultiEdit from "./building/multi-edit"; import MultiEdit from './building/multi-edit';
import Sidebar from "./building/sidebar"; import Sidebar from './building/sidebar';
import { Building, UserVerified } from "./models/building"; import { Building, UserVerified } from './models/building';
import Welcome from "./pages/welcome"; import Welcome from './pages/welcome';
import { PrivateRoute } from "./route"; import { PrivateRoute } from './route';
import { useLastNotEmpty } from "./hooks/use-last-not-empty"; import { useLastNotEmpty } from './hooks/use-last-not-empty';
import { Category } from "./config/categories-config"; import { Category } from './config/categories-config';
import { BuildingMapTileset } from "./config/tileserver-config"; import { BuildingMapTileset } from './config/tileserver-config';
import { import { defaultMapCategory, categoryMapsConfig } from './config/category-maps-config';
defaultMapCategory, import { useMultiEditData } from './hooks/use-multi-edit-data';
categoryMapsConfig, import { useAuth } from './auth-context';
} from "./config/category-maps-config"; import { sendBuildingUpdate } from './api-data/building-update';
import { useMultiEditData } from "./hooks/use-multi-edit-data";
import { useAuth } from "./auth-context";
import { sendBuildingUpdate } from "./api-data/building-update";
import "mapbox-gl/dist/mapbox-gl.css";
/** /**
* Load and render ColouringMap component on client-side only. * Load and render ColouringMap component on client-side only.
@ -41,212 +36,151 @@ import "mapbox-gl/dist/mapbox-gl.css";
* to all modules that import leaflet or react-leaflet. * to all modules that import leaflet or react-leaflet.
*/ */
const ColouringMap = loadable( const ColouringMap = loadable(
async () => (await import("./map/map")).ColouringMap, async () => (await import('./map/map')).ColouringMap,
{ ssr: false } { ssr: false }
); );
interface MapAppProps { interface MapAppProps {
building?: Building; building?: Building;
revisionId?: string; revisionId?: string;
user_verified?: object; user_verified?: object;
} }
/** Returns first argument, unless it's equal to the second argument - then returns undefined */ /** Returns first argument, unless it's equal to the second argument - then returns undefined */
function unless<V extends string, U extends V>( function unless<V extends string, U extends V>(value: V, unlessValue: U): Exclude<V, U> {
value: V, return value === unlessValue ? undefined : value as Exclude<V, U>;
unlessValue: U
): Exclude<V, U> {
return value === unlessValue ? undefined : (value as Exclude<V, U>);
} }
/** Returns the new value, unless it is equal to the current value - then returns undefined */ /** Returns the new value, unless it is equal to the current value - then returns undefined */
function setOrToggle<T>(currentValue: T, newValue: T): T { function setOrToggle<T>(currentValue: T, newValue: T): T {
if (newValue == undefined || newValue === currentValue) { if(newValue == undefined || newValue === currentValue){
return undefined; return undefined;
} else { } else {
return newValue; return newValue;
} }
} }
function useStateWithOptions<T>( function useStateWithOptions<T>(defaultValue: T, options: T[]): [T, (x: T) => void] {
defaultValue: T, const [value, setValue] = useState(defaultValue);
options: T[]
): [T, (x: T) => void] {
const [value, setValue] = useState(defaultValue);
const effectiveValue = options.includes(value) ? value : options[0]; const effectiveValue = options.includes(value) ? value : options[0];
const handleChange = useCallback((x) => setValue(x), []); const handleChange = useCallback((x) => setValue(x), []);
return [effectiveValue, handleChange]; return [effectiveValue, handleChange];
} }
export const MapApp: React.FC<MapAppProps> = (props) => { export const MapApp: React.FC<MapAppProps> = props => {
const { user } = useAuth(); const { user } = useAuth();
const [categoryUrlParam] = useUrlCategoryParam(); const [categoryUrlParam] = useUrlCategoryParam();
const [currentCategory, setCategory] = useState<Category>(); const [currentCategory, setCategory] = useState<Category>();
useEffect( useEffect(() => setCategory(unless(categoryUrlParam, 'categories')), [categoryUrlParam]);
() => setCategory(unless(categoryUrlParam, "categories")),
[categoryUrlParam]
);
const displayCategory = const displayCategory = useLastNotEmpty(currentCategory) ?? defaultMapCategory;
useLastNotEmpty(currentCategory) ?? defaultMapCategory;
const [selectedBuildingId, setSelectedBuildingId] = useUrlBuildingParam( const [selectedBuildingId, setSelectedBuildingId] = useUrlBuildingParam('view', displayCategory);
"view",
displayCategory
);
const [building, updateBuilding, reloadBuilding] = useBuildingData( const [building, updateBuilding, reloadBuilding] = useBuildingData(selectedBuildingId, props.building, user != undefined);
selectedBuildingId, const [userVerified, updateUserVerified, reloadUserVerified] = useUserVerifiedData(selectedBuildingId, props.user_verified);
props.building,
user != undefined
);
const [userVerified, updateUserVerified, reloadUserVerified] =
useUserVerifiedData(selectedBuildingId, props.user_verified);
const [revisionId, updateRevisionId] = useRevisionId(props.revisionId); const [revisionId, updateRevisionId] = useRevisionId(props.revisionId);
useEffect(() => { useEffect(() => {
updateRevisionId(building?.revision_id); updateRevisionId(building?.revision_id)
}, [building]); }, [building]);
const [mode] = useUrlModeParam(); const [mode] = useUrlModeParam();
const viewEditMode = unless(mode, "multi-edit"); const viewEditMode = unless(mode, 'multi-edit');
const [multiEditData, multiEditError] = useMultiEditData(); const [multiEditData, multiEditError] = useMultiEditData();
const selectBuilding = useCallback( const selectBuilding = useCallback((selectedBuilding: Building) => {
(selectedBuilding: Building) => { const currentId = selectedBuildingId;
const currentId = selectedBuildingId; updateBuilding(selectedBuilding);
updateBuilding(selectedBuilding); setSelectedBuildingId(setOrToggle(currentId, selectedBuilding?.building_id));
setSelectedBuildingId( }, [selectedBuildingId, setSelectedBuildingId, updateBuilding, building]);
setOrToggle(currentId, selectedBuilding?.building_id)
);
},
[selectedBuildingId, setSelectedBuildingId, updateBuilding, building]
);
const colourBuilding = useCallback( const colourBuilding = useCallback(async (building: Building) => {
async (building: Building) => { const buildingId = building?.building_id;
const buildingId = building?.building_id;
if (buildingId != undefined && multiEditError == undefined) { if(buildingId != undefined && multiEditError == undefined) {
try { try {
const updatedBuilding = await sendBuildingUpdate( const updatedBuilding = await sendBuildingUpdate(buildingId, multiEditData);
buildingId, updateRevisionId(updatedBuilding.revision_id);
multiEditData } catch(error) {
); console.error({ error });
updateRevisionId(updatedBuilding.revision_id); }
} catch (error) {
console.error({ error });
} }
} }, [multiEditError, multiEditData, currentCategory]);
},
[multiEditError, multiEditData, currentCategory]
);
const handleBuildingUpdate = useCallback( const handleBuildingUpdate = useCallback((buildingId: number, updatedData: Building) => {
(buildingId: number, updatedData: Building) => { // only update current building data if the IDs match
// only update current building data if the IDs match if(buildingId === selectedBuildingId) {
if (buildingId === selectedBuildingId) { updateBuilding(Object.assign({}, building, updatedData));
updateBuilding(Object.assign({}, building, updatedData)); } else {
} else { // otherwise, still update the latest revision ID
// otherwise, still update the latest revision ID updateRevisionId(updatedData.revision_id);
updateRevisionId(updatedData.revision_id); }
} }, [selectedBuildingId, building, updateBuilding, updateRevisionId]);
},
[selectedBuildingId, building, updateBuilding, updateRevisionId]
);
const handleUserVerifiedUpdate = useCallback( const handleUserVerifiedUpdate = useCallback((buildingId: number, updatedData: UserVerified) => {
(buildingId: number, updatedData: UserVerified) => { // only update current building data if the IDs match
// only update current building data if the IDs match if(buildingId === selectedBuildingId) {
if (buildingId === selectedBuildingId) { updateUserVerified(Object.assign({}, userVerified, updatedData)); // quickly show added verifications
updateUserVerified(Object.assign({}, userVerified, updatedData)); // quickly show added verifications reloadBuilding();
reloadBuilding(); reloadUserVerified(); // but still reload from server to reflect removed verifications
reloadUserVerified(); // but still reload from server to reflect removed verifications }
} }, [selectedBuildingId, updateUserVerified, reloadBuilding, userVerified]);
},
[selectedBuildingId, updateUserVerified, reloadBuilding, userVerified]
);
const categoryMapDefinitions = useMemo(
() => categoryMapsConfig[displayCategory],
[displayCategory]
);
const availableMapStyles = useMemo(
() => categoryMapDefinitions.map((x) => x.mapStyle),
[categoryMapDefinitions]
);
const [mapColourScale, setMapColourScale] =
useStateWithOptions<BuildingMapTileset>(undefined, availableMapStyles);
return ( const categoryMapDefinitions = useMemo(() => categoryMapsConfig[displayCategory], [displayCategory]);
<> const availableMapStyles = useMemo(() => categoryMapDefinitions.map(x => x.mapStyle), [categoryMapDefinitions]);
<PrivateRoute path="/:mode(edit|multi-edit)" />{" "} const [mapColourScale, setMapColourScale] = useStateWithOptions<BuildingMapTileset>(undefined, availableMapStyles);
{/* empty private route to ensure auth for editing */}
<Sidebar> return (
<Switch> <>
<Route exact path="/"> <PrivateRoute path="/:mode(edit|multi-edit)" /> {/* empty private route to ensure auth for editing */}
<Welcome /> <Sidebar>
</Route> <Switch>
<Route exact path="/multi-edit/:cat"> <Route exact path="/">
<MultiEdit category={displayCategory} /> <Welcome />
</Route> </Route>
<Route path="/:mode/:cat"> <Route exact path="/multi-edit/:cat">
<Categories <MultiEdit category={displayCategory} />
mode={mode || "view"} </Route>
building_id={selectedBuildingId} <Route path="/:mode/:cat">
<Categories mode={mode || 'view'} building_id={selectedBuildingId} />
<Switch>
<Route exact path="/:mode/:cat/:building/history">
<EditHistory building={building} />
</Route>
<Route exact path="/:mode/:cat/:building?">
<BuildingView
mode={viewEditMode}
cat={displayCategory}
building={building}
user_verified={userVerified ?? {}}
onBuildingUpdate={handleBuildingUpdate}
onUserVerifiedUpdate={handleUserVerifiedUpdate}
mapColourScale={mapColourScale}
onMapColourScale={setMapColourScale}
/>
</Route>
</Switch>
</Route>
<Route exact path="/:mode(view|edit|multi-edit)"
render={props => (<Redirect to={`/${props.match.params.mode}/categories`} />)}
/>
</Switch>
</Sidebar>
<ColouringMap
selectedBuildingId={selectedBuildingId}
mode={mode || 'basic'}
revisionId={revisionId}
onBuildingAction={mode === 'multi-edit' ? colourBuilding : selectBuilding}
mapColourScale={mapColourScale}
onMapColourScale={setMapColourScale}
categoryMapDefinitions={categoryMapDefinitions}
/> />
<Switch> </>
<Route exact path="/:mode/:cat/:building/history"> );
<EditHistory building={building} />
</Route>
<Route exact path="/:mode/:cat/:building?">
<BuildingView
mode={viewEditMode}
cat={displayCategory}
building={building}
user_verified={userVerified ?? {}}
onBuildingUpdate={handleBuildingUpdate}
onUserVerifiedUpdate={handleUserVerifiedUpdate}
mapColourScale={mapColourScale}
onMapColourScale={setMapColourScale}
/>
</Route>
</Switch>
</Route>
<Route
exact
path="/:mode(view|edit|multi-edit)"
render={(props) => (
<Redirect to={`/${props.match.params.mode}/categories`} />
)}
/>
</Switch>
</Sidebar>
<div
style={{
width: "100%",
height: "100%",
position: "relative",
float: "right",
overflow: "hidden",
}}
>
<ColouringMap
selectedBuildingId={selectedBuildingId}
mode={mode || "basic"}
revisionId={revisionId}
onBuildingAction={
mode === "multi-edit" ? colourBuilding : selectBuilding
}
mapColourScale={mapColourScale}
onMapColourScale={setMapColourScale}
categoryMapDefinitions={categoryMapDefinitions}
/>
</div>
</>
);
}; };

View File

@ -1,23 +1,17 @@
import React, { useEffect } from "react"; import React, { useEffect } from 'react';
import mapboxgl from "mapbox-gl"; import mapboxgl from 'mapbox-gl';
// Set your Mapbox access token // Set your Mapbox access token
mapboxgl.accessToken = mapboxgl.accessToken = 'pk.eyJ1IjoiYWxpLWFkbGkiLCJhIjoiY2xuM2JtYjV1MGE5djJrb2d5OGp1ZWNyNiJ9.gENyP4xX6ElLAeZFlE0aDg';
"pk.eyJ1IjoiYWxpLWFkbGkiLCJhIjoiY2xuM2JtYjV1MGE5djJrb2d5OGp1ZWNyNiJ9.gENyP4xX6ElLAeZFlE0aDg";
/* /**
Component to display a Mapbox map. * Component to display a Mapbox map.
*/ */
export function CityMap() { export function CityMap() {
const remote_css = fetch(
"https://api.tiles.mapbox.com/mapbox-gl-js/v0.53.0/mapbox-gl.css"
);
useEffect(() => { useEffect(() => {
const map = new mapboxgl.Map({ const map = new mapboxgl.Map({
container: "map", // container ID container: 'map', // container ID
style: "mapbox://styles/mapbox/streets-v12", // style URL style: 'mapbox://styles/mapbox/streets-v12', // style URL
center: [-73.5801403, 45.4962261], // starting position [lng, lat] center: [-73.5801403, 45.4962261], // starting position [lng, lat]
zoom: 15, // starting zoom zoom: 15, // starting zoom
}); });
@ -28,7 +22,10 @@ export function CityMap() {
return () => map.remove(); return () => map.remove();
}, []); }, []);
return <div id="map"></div>; return (
<div id="map" style={{ width: '100%', height: '100vh' }}></div>
);
} }
export default CityMap; export default CityMap;

View File

@ -73,14 +73,14 @@
} }
.theme-switcher { .theme-switcher {
top: 117px; top: 77px;
} }
.theme-switcher .btn { .theme-switcher .btn {
min-width: 340px; min-width: 340px;
} }
.data-switcher { .data-switcher {
top: 157px; top: 117px;
} }
.data-switcher .btn { .data-switcher .btn {
min-width: 340px; min-width: 340px;

View File

@ -1,5 +1,5 @@
.map-container { .map-container {
position: fixed; position: absolute;
top: 76px; /* sync with header positioning*/ top: 76px; /* sync with header positioning*/
bottom: 0; bottom: 0;
left: 0; left: 0;
@ -11,9 +11,7 @@
left: 470px; left: 470px;
} }
} }
.leaflet-container { .leaflet-container {height: 100%;
position: absolute;
height: 100%;
width: 100%; width: 100%;
} }
.leaflet-container .leaflet-control-zoom { .leaflet-container .leaflet-control-zoom {
@ -34,3 +32,4 @@
display: block; display: block;
} }
} }

View File

@ -1,209 +1,210 @@
import React, { import React, {
FC, FC,
useCallback, useCallback,
useEffect, useEffect,
useMemo, useMemo,
useState, useState,
useRef, useRef,
} from "react"; } from "react";
import { import {
AttributionControl, AttributionControl,
MapContainer, MapContainer,
ZoomControl, ZoomControl,
useMapEvent, useMapEvent,
Pane, Pane,
useMap, useMap,
} from "react-leaflet"; } from "react-leaflet";
// import 'leaflet/dist/leaflet.css'; import 'leaflet/dist/leaflet.css';
import "./map.css"; import "./map.css";
import { apiGet } from "../apiHelpers"; import { apiGet } from "../apiHelpers";
import { import {
initialMapViewport, initialMapViewport,
mapBackgroundColor, mapBackgroundColor,
MapTheme, MapTheme,
LayerEnablementState, LayerEnablementState,
} from "../config/map-config"; } from "../config/map-config";
import mapboxgl from "mapbox-gl"; import mapboxgl from "mapbox-gl";
import { Building } from "../models/building"; import { Building } from "../models/building";
import { CityMap } from "./layers/city-base-map-layer"; import { CityMap } from "./layers/city-base-map-layer";
import { CityBoundaryLayer } from "./layers/city-boundary-layer"; import { CityBoundaryLayer } from "./layers/city-boundary-layer";
import { BoroughBoundaryLayer } from "./layers/borough-boundary-layer"; import { BoroughBoundaryLayer } from "./layers/borough-boundary-layer";
import { BoroughLabelLayer } from "./layers/borough-label-layer"; import { BoroughLabelLayer } from "./layers/borough-label-layer";
import { ParcelBoundaryLayer } from "./layers/parcel-boundary-layer"; import { ParcelBoundaryLayer } from "./layers/parcel-boundary-layer";
import { HistoricDataLayer } from "./layers/historic-data-layer"; import { HistoricDataLayer } from "./layers/historic-data-layer";
import { HistoricMapLayer } from "./layers/historic-map-layer"; import { HistoricMapLayer } from "./layers/historic-map-layer";
import { FloodBoundaryLayer } from "./layers/flood-boundary-layer"; import { FloodBoundaryLayer } from "./layers/flood-boundary-layer";
import { ConservationAreaBoundaryLayer } from "./layers/conservation-boundary-layer"; import { ConservationAreaBoundaryLayer } from "./layers/conservation-boundary-layer";
import { VistaBoundaryLayer } from "./layers/vista-boundary-layer"; import { VistaBoundaryLayer } from "./layers/vista-boundary-layer";
import { HousingBoundaryLayer } from "./layers/housing-boundary-layer"; import { HousingBoundaryLayer } from "./layers/housing-boundary-layer";
import { CreativeBoundaryLayer } from "./layers/creative-boundary-layer"; import { CreativeBoundaryLayer } from "./layers/creative-boundary-layer";
import { BuildingBaseLayer } from "./layers/building-base-layer"; import { BuildingBaseLayer } from "./layers/building-base-layer";
import { BuildingDataLayer } from "./layers/building-data-layer"; import { BuildingDataLayer } from "./layers/building-data-layer";
import { BuildingNumbersLayer } from "./layers/building-numbers-layer"; import { BuildingNumbersLayer } from "./layers/building-numbers-layer";
import { BuildingHighlightLayer } from "./layers/building-highlight-layer"; import { BuildingHighlightLayer } from "./layers/building-highlight-layer";
import { Legend } from "./legend"; import { Legend } from "./legend";
import SearchBox from "./search-box"; import SearchBox from "./search-box";
import ThemeSwitcher from "./theme-switcher"; import ThemeSwitcher from "./theme-switcher";
import DataLayerSwitcher from "./data-switcher"; import DataLayerSwitcher from "./data-switcher";
import { BoroughSwitcher } from "./borough-switcher"; import { BoroughSwitcher } from "./borough-switcher";
import { ParcelSwitcher } from "./parcel-switcher"; import { ParcelSwitcher } from "./parcel-switcher";
import { FloodSwitcher } from "./flood-switcher"; import { FloodSwitcher } from "./flood-switcher";
import { ConservationAreaSwitcher } from "./conservation-switcher"; import { ConservationAreaSwitcher } from "./conservation-switcher";
import { HistoricDataSwitcher } from "./historic-data-switcher"; import { HistoricDataSwitcher } from "./historic-data-switcher";
import { HistoricMapSwitcher } from "./historic-map-switcher"; import { HistoricMapSwitcher } from "./historic-map-switcher";
import { VistaSwitcher } from "./vista-switcher"; import { VistaSwitcher } from "./vista-switcher";
import { CreativeSwitcher } from "./creative-switcher"; import { CreativeSwitcher } from "./creative-switcher";
import { HousingSwitcher } from "./housing-switcher"; import { HousingSwitcher } from "./housing-switcher";
import { BuildingMapTileset } from "../config/tileserver-config"; import { BuildingMapTileset } from "../config/tileserver-config";
import { useDisplayPreferences } from "../displayPreferences-context"; import { useDisplayPreferences } from "../displayPreferences-context";
import { CategoryMapDefinition } from "../config/category-maps-config"; import { CategoryMapDefinition } from "../config/category-maps-config";
mapboxgl.accessToken = mapboxgl.accessToken =
"pk.eyJ1IjoiYWxpLWFkbGkiLCJhIjoiY2xuM2JtYjV1MGE5djJrb2d5OGp1ZWNyNiJ9.gENyP4xX6ElLAeZFlE0aDg"; "pk.eyJ1IjoiYWxpLWFkbGkiLCJhIjoiY2xuM2JtYjV1MGE5djJrb2d5OGp1ZWNyNiJ9.gENyP4xX6ElLAeZFlE0aDg";
interface ColouringMapProps { interface ColouringMapProps {
selectedBuildingId: number; selectedBuildingId: number;
mode: "basic" | "view" | "edit" | "multi-edit"; mode: "basic" | "view" | "edit" | "multi-edit";
revisionId: string; revisionId: string;
onBuildingAction: (building: Building) => void; onBuildingAction: (building: Building) => void;
mapColourScale: BuildingMapTileset; mapColourScale: BuildingMapTileset;
onMapColourScale: (x: BuildingMapTileset) => void; onMapColourScale: (x: BuildingMapTileset) => void;
categoryMapDefinitions: CategoryMapDefinition[]; categoryMapDefinitions: CategoryMapDefinition[];
} }
export const ColouringMap: FC<ColouringMapProps> = ({ export const ColouringMap: FC<ColouringMapProps> = ({
mode, mode,
revisionId, revisionId,
onBuildingAction, onBuildingAction,
selectedBuildingId, selectedBuildingId,
mapColourScale, mapColourScale,
onMapColourScale, onMapColourScale,
categoryMapDefinitions, categoryMapDefinitions,
children, children,
}) => { }) => {
const { darkLightTheme, darkLightThemeSwitch, showLayerSelection } = const { darkLightTheme, darkLightThemeSwitch, showLayerSelection } =
useDisplayPreferences(); useDisplayPreferences();
const [position, setPosition] = useState(initialMapViewport.position); const [position, setPosition] = useState(initialMapViewport.position);
const [zoom, setZoom] = useState(initialMapViewport.zoom); const [zoom, setZoom] = useState(initialMapViewport.zoom);
const handleLocate = useCallback((lat: number, lng: number, zoom: number) => { const handleLocate = useCallback((lat: number, lng: number, zoom: number) => {
setPosition([lat, lng]); setPosition([lat, lng]);
setZoom(zoom); setZoom(zoom);
}, []); }, []);
const handleClick = useCallback( const handleClick = useCallback(
async (e) => { async (e) => {
const { lat, lng } = e.latlng; const { lat, lng } = e.latlng;
const data = await apiGet(`/api/buildings/locate?lat=${lat}&lng=${lng}`); const data = await apiGet(`/api/buildings/locate?lat=${lat}&lng=${lng}`);
const building = data?.[0]; const building = data?.[0];
onBuildingAction(building); onBuildingAction(building);
}, },
[onBuildingAction] [onBuildingAction]
); );
const mapContainer = useRef(null); const mapContainer = useRef(null);
const map = useRef(null); const map = useRef(null);
const [lng, setLng] = useState(-73.5801403); const [lng, setLng] = useState(-73.5801403);
const [lat, setLat] = useState(45.4962261); const [lat, setLat] = useState(45.4962261);
useEffect(() => { useEffect(() => {
if (map.current) return; // initialize map only once if (map.current) return; // initialize map only once
map.current = new mapboxgl.Map({ map.current = new mapboxgl.Map({
container: mapContainer.current, container: mapContainer.current,
style: "mapbox://styles/mapbox/streets-v12", style: "mapbox://styles/mapbox/streets-v12",
center: [lng, lat], center: [lng, lat],
zoom: zoom, zoom: zoom,
});
map.current.addControl(new mapboxgl.NavigationControl());
map.current.on("move", () => {
setLng(map.current.getCenter().lng.toFixed(4));
setLat(map.current.getCenter().lat.toFixed(4));
setZoom(map.current.getZoom().toFixed(2));
});
}); });
map.current.addControl(new mapboxgl.NavigationControl()); return (
<div
ref={mapContainer}
className="map-container"
style={{
position: "absolute",
top: "0",
bottom: "0",
left: "0",
right: "0",
}}
>
{mode !== "basic" && (
<>
<Legend
mapColourScaleDefinitions={categoryMapDefinitions}
mapColourScale={mapColourScale}
onMapColourScale={onMapColourScale}
/>
<ThemeSwitcher
onSubmit={darkLightThemeSwitch}
currentTheme={darkLightTheme}
/>
<DataLayerSwitcher />
{showLayerSelection == "enabled" ? (
<>
<BoroughSwitcher />
<ParcelSwitcher />
<FloodSwitcher />
<ConservationAreaSwitcher />
<HistoricMapSwitcher />
<HistoricDataSwitcher />
<VistaSwitcher />
<HousingSwitcher />
<CreativeSwitcher />
</>
) : (
<></>
)}
{/* TODO change remaining ones*/}
<SearchBox onLocate={handleLocate} />
</>
)}
</div>
);
};
map.current.on("move", () => { function ClickHandler({ onClick }: { onClick: (e) => void }) {
setLng(map.current.getCenter().lng.toFixed(4)); useMapEvent("click", (e) => onClick(e));
setLat(map.current.getCenter().lat.toFixed(4));
setZoom(map.current.getZoom().toFixed(2)); return null;
}
function MapBackgroundColor({ theme }: { theme: MapTheme }) {
const map = useMap();
useEffect(() => {
map.getContainer().style.backgroundColor = mapBackgroundColor[theme];
}); });
});
return ( return null;
<div }
ref={mapContainer}
className="map-container"
/*style={{
position: "absolute",
top: "0",
bottom: "0",
left: "0",
right: "0",
}}*/
>
{mode !== "basic" && (
<>
<Legend
mapColourScaleDefinitions={categoryMapDefinitions}
mapColourScale={mapColourScale}
onMapColourScale={onMapColourScale}
/>
<ThemeSwitcher
onSubmit={darkLightThemeSwitch}
currentTheme={darkLightTheme}
/>
<DataLayerSwitcher />
{showLayerSelection == "enabled" ? (
<>
<BoroughSwitcher />
<ParcelSwitcher />
<FloodSwitcher />
<ConservationAreaSwitcher />
<HistoricMapSwitcher />
<HistoricDataSwitcher />
<VistaSwitcher />
<HousingSwitcher />
<CreativeSwitcher />
</>
) : (
<></>
)}
{/* TODO change remaining ones*/}
<SearchBox onLocate={handleLocate} />
</>
)}
</div>
);
};
function ClickHandler({ onClick }: { onClick: (e) => void }) { function MapViewport({
useMapEvent("click", (e) => onClick(e)); position,
zoom,
}: {
position: [number, number];
zoom: number;
}) {
const map = useMap();
return null; useEffect(() => {
} map.setView(position, zoom);
}, [position, zoom]);
function MapBackgroundColor({ theme }: { theme: MapTheme }) { return null;
const map = useMap(); }
useEffect(() => {
map.getContainer().style.backgroundColor = mapBackgroundColor[theme];
});
return null;
}
function MapViewport({
position,
zoom,
}: {
position: [number, number];
zoom: number;
}) {
const map = useMap();
useEffect(() => {
map.setView(position, zoom);
}, [position, zoom]);
return null;
}

View File

@ -93,6 +93,7 @@ function renderHTML(context, data, req, res) {
`<!doctype html> `<!doctype html>
<html lang=""> <html lang="">
<head> <head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charset="utf-8" /> <meta charset="utf-8" />
@ -127,6 +128,8 @@ function renderHTML(context, data, req, res) {
font-style: normal; font-style: normal;
} }
</style> </style>
<link href="https://api.mapbox.com/mapbox-gl-js/v2.14.1/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v2.14.1/mapbox-gl.js"></script>
${ ${
assets.client.css assets.client.css
? `<link rel="stylesheet" href="${assets.client.css}">` ? `<link rel="stylesheet" href="${assets.client.css}">`