Search code examples
reactjsgoogle-mapsreact-hooksreact-google-mapsrecompose

Perform action when user clicks on map or marker in react-google-maps


I am trying to implement google maps in my react project using react-google-maps package.

The map is visible however I am not able to perform other event actions like onClick. The documentation and examples are not useful as they are using recompose. However recompose is no longer needed due to release of hooks in React v16.

Below is the code, please point out what I am doing wrong. Also tips of how to write hooks based code instead of recompose will be extremely helpful. Also I am a React newbie, so might have made obvious mistake

function handleMarkerClick() {
  console.log("function called");
}

const MyMapComponent = withScriptjs(
  withGoogleMap(props => ( <GoogleMap defaultZoom = {13} defaultCenter = {{ lat: 19.1998, lng: 72.8426 }}> 
  {props.isMarkerShown && ( <Marker position = { { lat: 19.1998, lng: 72.8426 }} onClick = { props.onMarkerClick } />)} 
  </GoogleMap>
  ))
);

function Register() {
  return ( <Wrapper>
      <MyMapComponent isMarkerShown = { true }
      googleMapURL = "https://maps.googleapis.com/maps/api/js?key=*******&v=3.exp&libraries=geometry,drawing,places"
      loadingElement = { < div style = {
          {
            height: `100%`
          }
        }
        />}
        containerElement = { < div style = {
            {
              height: `100vh`
            }
          }
          />}
          mapElement = { < div style = {
              {
                height: `100%`
              }
            }
            />} / >
             < /
            Wrapper>
          );
        }

export default Register;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>


Solution

  • You need to update the code like onClick = { (event) => { props.onMarkerClick (event) } } in Marker component then you get output lat and lang from event in handleMarkerClick(event) { console.log(event.latLng.lat())}