在React中向谷歌地图添加自定义样式



我正试图在我的React应用程序中向谷歌地图添加自定义样式,在那里我可以显示地图,但在定义地图的样式时遇到了困难。

我已经包含了评论代码,说明我如何能够使用VanillaJS设计地图样式,但在React中不断出现错误。

const googleMapRef = useRef(null);
const googleMap = useRef(null);
const marker = useRef(null);
const createGoogleMap = () =>
new window.google.maps.Map(googleMapRef.current, {
center: {
lat: userLocation.lat,
lng: userLocation.lng,
},
zoom: 16,
disableDefaultUI: true,
gestureHandling: 'none',
mapTypeControlOptions: {
mapTypeIds: ['roadmap', 'satellite', 'hybrid', 'terrain', 'map'],
},
});
const createMarker = () =>
new window.google.maps.Marker({
position: { lat: userLocation.lat, lng: userLocation.lng },
map: googleMap.current,
icon: {
path: window.google.maps.SymbolPath.CIRCLE,
scale: 5,
fillColor: '#1652f0',
fillOpacity: 1,
strokeColor: '#1652f0',
strokeWeight: 8,
strokeOpacity: 0.5,
},
});
useEffect(() => {
const googleMapScript = document.createElement('script');
googleMapScript.src = `https://maps.googleapis.com/maps/api/js?key=${GOOGLE_MAP_API_KEY}`;
window.document.body.appendChild(googleMapScript);
googleMapScript.addEventListener('load', () => {
googleMap.current = createGoogleMap();
marker.current = createMarker();
});
}, []);
const mapStyles = () =>
new window.google.maps.StyledMapType(
[
{
elementType: 'geometry',
stylers: [
{
color: '#f5f5f5',
},
],
},
... 
],
{ name: 'Map' }
);
// createGoogleMap.mapTypes.set('map', mapStyles); <-- This is how you would normally bind the styles to the map in Vanilla JS but can't seem to do it in React
// map.setMapTypeId('folded_map');
return (
<div>
<div id="map" ref={googleMapRef} style={divStyles} />
</div>
);

谷歌地图样式器:https://mapstyle.withgoogle.com/

使用谷歌地图进行react:谷歌地图react

npm install --save google-maps-react

将样式添加到GoogleMap组件

<GoogleMap
options={{
styles: [...]
}}
/>

最新更新