首页 > 解决方案 > 在 React 中向 Google 地图添加自定义样式

问题描述

我正在尝试在我的 React 应用程序中向 Google Map 添加自定义样式,我可以在其中显示地图,但是在为地图定义样式时遇到了困难。

我在注释代码中包含了如何使用 Vanilla JS 设置地图样式,但在 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>
);

标签: reactjsgoogle-maps

解决方案


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

使用谷歌地图进行反应:google-maps-react

npm install --save google-maps-react

将样式添加到 GoogleMap 组件

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

推荐阅读