I am trying to render markers using Mapbox GL JS in a React / Next application. The map is rendering, but the markers are not. Here is my code:
import { useEffect, useRef } from "react";
import { Container, Box, Button } from '@mui/material';
import { styled } from '@mui/system';
import mapboxgl from "mapbox-gl";
mapboxgl.accessToken = [ACCESS TOKEN];
import { useRouter } from 'next/router'
const MapContainer = styled(Box)`
width: 70%;
height: 100vh;
@media (max-width: 600px) {
height: 50vh;
width: 100%;
}
`;
const MainContainer = styled(Container)({
display: 'flex',
flexDirection: 'row'
});
export default function Home() {
const mapContainer = useRef(null);
const router = useRouter();
useEffect(() => {
const map = new mapboxgl.Map({
container: mapContainer.current,
style: "mapbox://styles/mapbox/streets-v11",
center: [-74.0060, 40.7128], // Starting position [lng, lat]
zoom: 12,
});
map.addControl(new mapboxgl.NavigationControl(), "top-right");
var el = document.createElement('div');
el.className = 'marker';
el.style.backgroundImage = 'url(https://placekitten.com/g/500)';
el.style.width = '100px';
el.style.height = '100px';
new mapboxgl.Marker(el)
.setLngLat([-74.0060, 40.7128]) // Marker position [lng, lat]
.addTo(map);
// Clean up on unmount
return () => {
map.remove();
};
});
return (
<MainContainer disableGutters maxWidth={false}>
<MapContainer ref={mapContainer} />
</MainContainer>
);
}
Fwiw, the navigation control placed in the top right also doesn't appear, so it doesn't seem to be a marker-specific issue. Maybe it has to do with how I am rendering the map in the useEffect. Please advise :)
You have to import the stylesheet!