Skip to content

Commit

Permalink
[Task] #123, add mapbox token in react
Browse files Browse the repository at this point in the history
  • Loading branch information
Type-Style committed Sep 6, 2024
1 parent 39163d9 commit 4fc6b1a
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 8 deletions.
2 changes: 1 addition & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ app.set('trust proxy',true);
// routes
app.get(['/', '/login'], (req, res) => {
logger.log(req.ip + " - " + res.locals.ip, true);
res.render("index");
res.render("index", {"mapbox": process.env.MAPBOX, "root": process.env.ROOT});
});

app.use('/write', writeRouter);
Expand Down
26 changes: 25 additions & 1 deletion src/client/components/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useColorScheme } from '@mui/material/styles';
import { useMediaQuery } from '@mui/material';
import Start from '../pages/Start';
import Login from '../pages/Login';
import axios from "axios";

export const Context = createContext([]);

Expand Down Expand Up @@ -38,18 +39,41 @@ const router = createBrowserRouter([
}
]);


const App = () => {
const [userInfo, setUserInfo] = useState(convertJwt());
const [isLoggedIn, setLogin] = useState(loginDefault(userInfo));
const { mode, setMode } = useColorScheme();
const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
const [mapToken, setMapToken] = useState<string | null>(null);

useEffect(() => {
setMode(prefersDarkMode ? "dark" : "light");
}, [prefersDarkMode, setMode]);


useEffect(() => {
if (!isLoggedIn) return;
const fetchToken = async () => {
try {
const token = localStorage.getItem("jwt");
const response = await axios.get("/read/maptoken", {
headers: {
Authorization: `Bearer ${token}`,
},
});

setMapToken(response.data.mapbox);
} catch (error) {
console.error("Error fetching map token:", error);
}
};

fetchToken();
}, [isLoggedIn]);

return (
<Context.Provider value={[isLoggedIn, setLogin, userInfo, setUserInfo, mode, setMode, prefersDarkMode]}>
<Context.Provider value={[isLoggedIn, setLogin, userInfo, setUserInfo, mode, setMode, prefersDarkMode, mapToken]}>
<RouterProvider router={router} />
</Context.Provider>
);
Expand Down
8 changes: 5 additions & 3 deletions src/client/components/Map.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,18 +54,20 @@ const MultiColorPolyline = ({ cleanEntries }: { cleanEntries: Models.IEntry[] })
});
}


function Map({ entries }: { entries: Models.IEntry[] }) {
if (!entries?.length) {
return <span className="noData cut">No Data to be displayed</span>
}
const [, , , , mode] = useContext(Context);

const [, , , , mode, , , mapToken] = useContext(Context);
const [mapStyle, setMapStyle] = useState(mode);

const lastEntry = entries.at(-1);
const cleanEntries = entries.filter((entry) => !entry.ignore);
const cleanEntriesWithoutLast = cleanEntries.slice(0, -1);


const replaceKeyword = "XXXREPLACEXXX";

// Function to create custom icon with dynamic className
function createCustomIcon(entry: Models.IEntry) {
Expand Down Expand Up @@ -128,7 +130,7 @@ function Map({ entries }: { entries: Models.IEntry[] }) {
>
<TileLayer
attribution={layer.attribution}
url={layer.url}
url={layer.url.includes(replaceKeyword) ? layer.url.replace(replaceKeyword, mapToken) : layer.url}
tileSize={layer.size || 256}
zoomOffset={layer.zoomOffset || 0}

Expand Down
10 changes: 8 additions & 2 deletions src/client/components/MiniMap.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import React from 'react'
import React, { useContext } from 'react'
import { MapContainer, TileLayer } from "react-leaflet";
import { MapRecenter } from "./MapCenter";
import { Context } from "./App";

export default function MiniMap({ layer, lastEntry, index }: client.MiniMapProps) {

const [, , , , , , , mapToken] = useContext(Context);

const replaceKeyword = "XXXREPLACEXXX";

function handleClick() {
const elements = document.querySelectorAll('input.leaflet-control-layers-selector');
const el = elements[index] as HTMLInputElement | null;
Expand All @@ -24,7 +30,7 @@ export default function MiniMap({ layer, lastEntry, index }: client.MiniMapProps
<MapRecenter lat={lastEntry.lat} lon={lastEntry.lon} zoom={15} fly={false} />
<TileLayer
attribution={layer.attribution}
url={layer.url}
url={layer.url.includes(replaceKeyword) ? layer.url.replace(replaceKeyword, mapToken) : layer.url}
tileSize={layer.size || 256}
zoomOffset={layer.zoomOffset || 0}
/>
Expand Down
2 changes: 1 addition & 1 deletion src/client/scripts/layers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export const layers:client.Layer[] = [
{
name: "Mapbox Satelite Streets",
attribution: '&copy; <a href="https://www.mapbox.com/" target="_blank">Mapbox</a>',
url: 'https://api.mapbox.com/styles/v1/mapbox/satellite-streets-v12/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoidHlwZS1zdHlsZSIsImEiOiJjbGJ4aG14enEwZ2toM3BvNW5uanhuOGRvIn0.7TUEM9vA-EYSt3WW_bcsAA',
url: `https://api.mapbox.com/styles/v1/mapbox/satellite-streets-v12/tiles/{z}/{x}/{y}?access_token=XXXREPLACEXXX`,
markerStyle: "dark",
size: 512,
zoomOffset: -1
Expand Down

0 comments on commit 4fc6b1a

Please sign in to comment.