无法弄清楚,请使用 MAPBOX API 代替
我正在尝试将高级标记添加到我的反应项目中,但我无法使其工作。我认为造成这种情况的原因是如图所示的设置。有谁知道我如何将此设置更改为 true? 设置
这是我的代码:
const mapOptions = {
madId: process.env.NEXT_PUBLIC_MAP_ID,
center: { lat: 43.66, lng: -79.39 },
zoom: 10,
disableDefaultUI: true,
}
function MyMap() {
const [ map, setMap ] = useState();
const ref = useRef();
useEffect(() => {
setMap(new google.maps.Map(ref.current, mapOptions))
}, [])
return (
<>
<div ref={ref} id="map"/>
{map && <City map={map} />}
</>
)
}
const cityData = {
A: {
name: "Toronto",
position: { lat: 43.66, lng: -79.39 }
},
B: {
name: "Amsterdam",
position: { lat: 53.66, lng: -79.39 }
}
}
function City({map}) {
const [ data, setData ] = useState(cityData);
return (
<>
{Object.entries(data).map(([key, city]) => (
<Marker key={key} map={map} position={city.position}>
<div className="marker">
<h2>{city.name}</h2>
</div>
</Marker>
))}
</>
)
}
function Marker({map, children, position}) {
const markerRef = useRef();
const rootRef = useRef();
useEffect(() => {
if (!rootRef.current) {
const container = document.createElement("div");
rootRef.current = createRoot(container);
markerRef.current = new google.maps.marker.AdvancedMarkerView({
position,
content: container,
});
}
}, []);
useEffect(() => {
rootRef.current.render(children)
markerRef.current.position = position;
console.log(markerRef.current.map = map);
}, [map, position, children])
}
以及我在渲染中的参考:
<Wrapper apiKey={process.env.REACT_APP_GOOGLE_API_KEY} version="beta" libraries={["marker"]}>
<MyMap />
</Wrapper>
受到 Google 制作的这段视频的启发:https://www.youtube.com/watch?v=8kxYqoY2WwE
您需要将
mapId
添加到地图初始化选项中:
The Map ID of the map. This parameter cannot be set or changed after a map is instantiated. Map.DEMO_MAP_ID can be used to try out features that require a map ID but which do not require cloud enablement.
mapId: 'DEMO_MAP_ID'