0

onGoogleApiLoaded 未在位置数据更改时调用,有没有办法实现这一点?

我尝试使用 useEffect 加载标记,但随后我必须将地图和地图对象保存在 useRef 以及标记中

有没有更简单的方法来实现这一目标?

  import { useEffect, useRef } from 'react';
  import GoogleMapReact from 'google-map-react';

  export type SimpleMapProps = {
    locations: any[];
  };

  export default function SimpleMap({ locations }: SimpleMapProps) {
    const defaultProps =
      locations.length > 0
        ? {
            center: {
              lat: locations[0].Lat,
              lng: locations[0].Lon
            },
            zoom: 11
          }
        : {
            center: {
              lat: 0,
              lng: 0
            },
            zoom: 11
          };

    const handleApiLoadData = (map: any, maps: any) => {
      for (let i = 0; i < locations.length; i++) {
        const { Lat, Lon, hn, cur, rate } = locations[i];

        const marker = new maps.Marker({
          animation: maps.Animation.DROP,
          position: { lat: Lat, lng: Lon },
          map
        });

        marker.customInfowindow = new maps.InfoWindow({
          content: `<div>${hn} </br> (${cur} ${rate})</div>`
        });

        marker.addListener('click', () => {
          marker.customInfowindow.open(map, marker);
        });
      }
    };

    return (
      // Important! Always set the container height explicitly
      <div style={{ height: '50vh', width: '100%' }}>
        <GoogleMapReact
          bootstrapURLKeys={{
            key: 'XXXXXXXXXXXXXXX'
          }}
          center={defaultProps.center}
          zoom={defaultProps.zoom}
          yesIWantToUseGoogleMapApiInternals
          onGoogleApiLoaded={({ map, maps }) => handleApiLoadData(map, maps)}
        />
      </div>
    );
  }
4

0 回答 0