I recently made my first app on React. I had a d3 map that looks a bit old now, so I decided to switch to Mapbox. The data transmitted is a list of country names and a percentage. The goal is to visualize each country and its percentage. I wrote all my code, and everything seemed to go well. However, I now get this error on line 19 : "Geocoder is not defined". I specify that I have installed :
- mapbox-gl
- react-mapbox-gl
- react-map-gl-geocoder Can someone explain to me where my mistake came from?
import React, { useRef, useEffect } from "react";
import mapboxgl from "mapbox-gl";
import MapGeocoder from "react-map-gl-geocoder";
const MapChart = ({ data }) => {
const mapContainer = useRef(null);
useEffect(() => {
mapboxgl.accessToken =
"**********";
const map = new mapboxgl.Map({
container: mapContainer.current,
style: "mapbox://styles/mapbox/streets-v12",
center: [0, 0],
zoom: 1
});
// Geocode the data points to get the latitude and longitude
const geocoder = new MapGeocoder({
accessToken: mapboxgl.accessToken
});
data.forEach((datapoint) => {
geocoder.geocode(datapoint.country, (error, result) => {
if (error) {
console.error(error);
return;
}
const [longitude, latitude] = result.features[0].geometry.coordinates;
const marker = new mapboxgl.Marker({
color: "#" + ((Math.random() * 0xffffff) << 0).toString(16)
}).setLngLat([longitude, latitude]);
marker.setPopup(
new mapboxgl.Popup().setHTML(`
<h3>${datapoint.country}</h3>
<p>${datapoint.percentage}%</p>
`)
);
marker.addTo(map);
});
});
}, [data]);
return <div ref={mapContainer} style={{ width: "100%", height: "400px" }} />;
};
export default MapChart;