代码之家  ›  专栏  ›  技术社区  ›  Nick

在React中为Google Map添加自定义样式

  •  0
  • Nick  · 技术社区  · 4 年前

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

    我在注释代码中介绍了如何使用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>
    );
    
    1 回复  |  直到 4 年前
        1
  •  0
  •   xIsra    4 年前

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

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

    npm install --save google-maps-react
    

    将样式添加到GoogleMap组件

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