如何使用带有功能组件的 react-google-maps 访问 Map 对象?

How to access to the Map object with react-google-maps with functional components?

我无法使用 react-google-maps 库访问地图对象属性

我想获得原始方法,例如 "getBouds"

我在文档中找不到任何信息,我尝试使用 ref 和 onIdle。

import React, { useState, useMemo, useEffect, useRef } from 'react';
import { compose, withProps } from 'recompose';
import {
  withScriptjs,
  withGoogleMap,
  GoogleMap,
  Marker,
} from 'react-google-maps';
import { MarkerWithLabel } from 'react-google-maps/lib/components/addons/MarkerWithLabel';

import classes from './map.module.scss';
import Test from './test';

const loger = () => console.log(google.maps.Map.getBounds());

const MyMapComponent = compose(
  withProps({
    googleMapURL:
      'https://maps.googleapis.com/maps/api/js?key=YOURKEY&libraries=drawing',
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div className={classes.test} />,
    mapElement: <div className={classes.subtest} />,
  }),
  withScriptjs,
  withGoogleMap
)((props) => {
  const header = useRef();

  return (
    <GoogleMap
      defaultZoom={15}
      defaultCenter={{ lat: -34.5877058, lng: -58.4354737 }}
      // onBoundsChanged={() => console.log('test')}
      onIdle={props.onMapIdle}
    >
      <MarkerWithLabel
        position={{ lat: -34.5811123, lng: -58.4287612 }}
        labelAnchor={new google.maps.Point(0, 0)}
        clickable
        zIndex={0}
        // onClick={() => console.log('test')}
        labelStyle={{
          backgroundColor: 'white',
          fontSize: '16px',
        }}
      >
        <div>
          <h1
            onClick={loger}
            style={{ backgroundColor: 'red', zIndex: '1000000' }}
            ref={header}
          >
            Test
          </h1>
          <h2>other</h2>
          <h2>other</h2>
          <h2>other</h2>
          <h2>other</h2>
          <h2>other</h2>
        </div>
      </MarkerWithLabel>
    </GoogleMap>
  );
});

const MyFancyComponent = () => {
  const [isMarkerShown, setisMarkerShown] = useState(false);

  const delayedShowMarker = () => {
    setTimeout(() => {
      setisMarkerShown(true);
    }, 1000);
  };

  const handleMarkerClick = () => {
    // setisMarkerShown(false);
    // delayedShowMarker();
    console.log('test');
  };

  useEffect(() => {
    // delayedShowMarker();
  }, []);

  return (
    <MyMapComponent
      isMarkerShown={isMarkerShown}
      // onMarkerClick={handleMarkerClick}
      onMapIdle={() => console.log('map·is·ready')}

    />
  );
};

export default MyFancyComponent;

我想访问 Map 方法,例如 getBounds() 以仅呈现适合当前边界的标记。

拨打getBounds():

    <GoogleMap
        {...mapProps}
        ref={ref => {
            if (ref) {
                console.log(ref.getBounds());
            }
        }}
    >
        {children}
    </GoogleMap>