Vignesh
Vignesh

Reputation: 11

How to add custom buttons to react-google-maps?

I'm trying to add an in app map to my application. In this I need to add a button which will console log ("Hi I'm here") when clicked.

Package used here is "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>

Upvotes: 1

Views: 2531

Answers (1)

John Vert
John Vert

Reputation: 86

If you are using React >= 16.8 (hooks) I suggest you update to @react-google-maps/api. Then you can create a reusable MapControl with a few lines of code:

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>;
};

Then you can place a <MapControl> inside your <GoogleMap> using any content you like

<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>

Upvotes: 4

Related Questions