【问题标题】:How to add custom buttons to react-google-maps?如何将自定义按钮添加到 react-google-maps?
【发布时间】:2021-12-03 09:50:45
【问题描述】:

我正在尝试将应用内映射添加到我的应用程序。在此我需要添加一个按钮,该按钮将在单击时进行控制台日志(“嗨,我在这里”)。

这里使用的包是“react-google-maps”

const handleOnLoad = GoogleMap => {
  const controlButtonDiv = document.createElement('div');
  ReactDOM.render(<CustomControl onClick={() => console.log('Hi I'm Here')} />, controlButtonDiv);
  GoogleMap.controls[window.google.maps.ControlPosition.TOP_RIGHT].push(controlButtonDiv);
};

<GoogleMap
  defaultZoom={16}
  defaultCenter={{ lat: this.props.latVal, lng: this.props.longVal}}
  onTilesLoaded={GoogleMap => handleOnLoad(GoogleMap)}
  >
    <Marker 
    position={this.state.progress[this.state.progress.length - 1]}
    icon={{
    url: 'https://images.vexels.com/media/users/3/154573/isolated/preview/bd08e000a449288c914d851cb9dae110-hatchback-car-top-view-silhouette-by-vexels.png',
    scaledSize: new window.google.maps.Size(50, 50),
    anchor: { x: 10, y: 10 }
    }}
    />
    <Polyline 
    path={this.state.progress} 
    options={{ strokeColor: "#FF0000" }} 
    />
    <Circle 
    defaultCenter={{lat: this.props.latVal, lng: this.props.longVal}} 
    radius={parseInt(this.props.geofence)}
    options={{strokeColor: "#ff0000"}}
    />          
  </GoogleMap>

【问题讨论】:

    标签: reactjs react-google-maps


    【解决方案1】:

    如果你使用 React >= 16.8 (hooks),我建议你更新到@react-google-maps/api。然后你可以用几行代码创建一个可重用的 MapControl:

    interface MapControlProps {
      position: keyof typeof google.maps.ControlPosition;
    }
    const MapControl = (props: React.PropsWithChildren<MapControlProps>) => {
      const map = useGoogleMap();
      const ref = useRef();
      useEffect(() => {
        if (map && ref) {
          map.controls[window.google.maps.ControlPosition[props.position]].push(
            ref.current
          );
        }
      }, [map, ref]);
      return <div ref={ref}>{props.children}</div>;
    };
    

    然后您可以使用您喜欢的任何内容在您的&lt;GoogleMap&gt; 中放置一个&lt;MapControl&gt;

    <GoogleMap
      defaultZoom={16}
      defaultCenter={{ lat: this.props.latVal, lng: this.props.longVal}}
      onTilesLoaded={GoogleMap => handleOnLoad(GoogleMap)}
      >
      <MapControl position="LEFT_BOTTOM">
        <button
          style={{ backgroundColor: "red" }}
          onClick={() => console.log('Hi I'm Here')}
        >
          CLICK ME
        </button>
        <input placeholder="type some stuff" />
      </MapControl>
    </GoogleMap>
    

    【讨论】:

      猜你喜欢
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      相关资源
      最近更新 更多