Google Maps Ground Overlay是否未定义?

时间:2019-06-04 23:28:15

标签: javascript reactjs google-maps

我正在尝试使用https://codesandbox.io/s/lx947qjv0z在此代码沙箱GroundOverlay from this example上扩展项目。我已将存储库分叉到此沙盒https://codesandbox.io/s/google-maps-with-react-hooks-xywlb中。

我基本上添加的是google/GroundOverlay.jsx中的一个组件:

import { useState, useEffect } from "react";

export default function GroundOverlay({
  url,
  bounds,
  maps,
  map,
  events,
  opacity
}) {
  const [groundOverlay, setGroundOverlay] = useState();

  useEffect(() => {
    setGroundOverlay(new maps.GroundOverlay(url, bounds));
  });

  useEffect(() => {
    if (map) {
      groundOverlay.setMap(map);
    }

    if (opacity) {
      groundOverlay.setOpacity(opacity);
    }
  }, [map, opacity, groundOverlay]);

  return null;
}

并将此组件作为<Map>的子级添加到顶级Consumer.jsx中:

import React, { useState } from "react";
import Map from "./google/Map";
import Marker from "./google/Marker";
import TransitLayer from "./google/TransitLayer";
import GroundOverlay from "./google/GroundOverlay";
import getPlaces from "./utils/getPlaces";

export default function Consumer() {
  const places = getPlaces();
  const [placeIndex, setPlaceIndex] = useState(0);
  const [bound, setBound] = useState({});
  const [transitLayerEnabled, setTransitLayerEnabled] = useState(false);

  return (
    <div>
      <h3>Basic google maps with React hooks </h3>
      <Map
        zoom={10}
        center={{ lat: places[placeIndex].lat, lng: places[placeIndex].lng }}
        events={{ onBoundsChanged: arg => setBound(arg) }}
      >
        <TransitLayer enabled={transitLayerEnabled} />
        {places.map((m, index) => (
          <Marker
            key={m.id}
            active={placeIndex === index}
            title={"marker id: " + m.id}
            position={{ lat: m.lat, lng: m.lng }}
            events={{
              onClick: () => window.alert(`marker ${index} clicked`)
            }}
          />
        ))}
        <GroundOverlay
          url='https://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg'
          bounds={{
            north: 40.773941,
            south: 40.712216,
            east: -74.12544,
            west: -74.22655
          }}
          opacity={0.5}
        />
      </Map>
      <button
        className="btn"
        onClick={() => setPlaceIndex((placeIndex + 1) % places.length)}
      >
        Next place
      </button>
      <br />
      <button
        className="btn"
        onClick={() => setTransitLayerEnabled(!transitLayerEnabled)}
      >
        Toggle transit layer
      </button>
      <br />
      Current place id: {places[placeIndex].id}
      <br />
      Map bounds: {bound.toString()}
    </div>
  );
}

但是,如果我使用npm start运行此命令,则会在控制台中收到以下错误:

GroundOverlay.jsx? [sm]:19 Uncaught TypeError: Cannot read property 'setMap' of undefined

我不确定为什么groundOverlay状态变量是undefined,因为它是在第一个useEffect()中构造的?

0 个答案:

没有答案