我正在尝试在React/Next应用程序中使用Mapbox GL JS来渲染标记。地图正在渲染,但标记没有。这是我的代码:
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],
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])
.addTo(map);
return () => {
map.remove();
};
});
return (
<MainContainer disableGutters maxWidth={false}>
<MapContainer ref={mapContainer} />
</MainContainer>
);
}
Fwiw,位于右上角的导航控件也没有出现,所以这似乎不是一个特定于标记的问题。也许这与我在useEffect中渲染地图的方式有关。请告知:)