I'm trying to add a Layer to my mapbox map only when a condition is met. In this case, the condition is if a tube station name is guessed correctly, then the Layer i.e. station name corresponding to the guessedStation should be added to the map.
This is my code so far:
import styles from "./page.module.css";
import React, { useRef, useEffect, useState } from "react";
import mapboxgl from "mapbox-gl";
import data from "../../data/tcl.json";
console.log(data)
interface MapProps {
guessedStation: string | null;
}
const Map: React.FC<MapProps> = ({ guessedStation }) => {
const mapContainer = useRef<HTMLDivElement | null>(null); //create a reference to a <div> element that will contain the map
useEffect(() => {
const map = new mapboxgl.Map({
container: mapContainer.current!,
accessToken: process.env.NEXT_PUBLIC_MAPBOX_TOKEN,
style: "*(hidden)*",
center: [4.840872, 45.74474],
zoom: 12.4,
minZoom: 10.5,
maxBounds: [
//coords to limit the map panning
[4.63, 45.57], // Southwest coordinates
[5.19, 45.92], // Northeast coordinates
],
});
map.on("load", () => {
map.addSource("tcl", {
type: "geojson",
data: data as any,
});
if (guessedStation) {
const matchingStations = data.features.filter((feature: any) => feature.properties.nom === guessedStation);
matchingStations.forEach((station: any) => {
map.addLayer({
id: `tcl-label-${station.properties.id}`,
type: "symbol",
source: "tcl",
layout: {
"text-field": station.properties.nom,
"text-size": 12,
"text-offset": [0, -1]
},
paint: {
"text-color": "black",
"text-halo-color": "#ffffff",
"text-halo-width": 0.5
},
filter: ["==", "id", station.properties.id] // Filter by station id
});
});
}
});
return () => map.remove();
}, [guessedStation, data]);
return <div ref={mapContainer} className={styles.map} />;
};
export default Map;
I've tried mapping over the data and adding different conditions