Добавление пользовательских стилей в карту Google в React

#reactjs #google-maps

#reactjs #google-карты

Вопрос:

Я пытаюсь добавить пользовательские стили на карту Google в своем приложении 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:

Стилизатор карт Google: https://mapstyle .withgoogle.com /

Используйте карты Google для реакции: google-maps-react

 npm install --save google-maps-react
  

Добавьте стили в компонент GoogleMap

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