Search code examples
javascriptreactjsreact-google-maps

Getting lat/lng from google map using react-google-maps


I have my map component

const MyMapComponent = withScriptjs(
  withGoogleMap(props => (
    <GoogleMap
      defaultZoom={8}
      defaultCenter={{ lat: props.lat, lng: props.lng }}
      onClick={e => console.log(e)}
    >
      {props.isMarkerShown && (
        <Marker position={{ lat: props.lat, lng: props.lng }} />
      )}
      <MarkerClusterer averageCenter enableRetinaIcons gridSize={60}>
        {props.markers.map(marker => (
          <CustomMarker
            key={marker.id}
            marker={marker}

          />
        ))}
      </MarkerClusterer>
    </GoogleMap>
  ))
);
export default MyMapComponent;

And I have my app component that return this code

  return (
      <div className="container">
        <div className="map">
// myMapComponent imported as Map
          <Map
            onMapClick={this.onMapClick}

            googleMapURL="https://maps.googleapis.com/maps/api/js?v=3.exp&key=YOUR_API_KEY"
            loadingElement={<div style={{ height: `100%` }} />}
            containerElement={<div style={{ height: `95vh` }} />}
            mapElement={<div style={{ height: `100%` }} />}
            lat={this.state.lat}
            lng={this.state.lng}
            markers={filteredResturants}

          />
        </div>

      </div>
    );

I want have lat/lng when a user clicks on map. The most straightforward way I found in every answer is to have onClick event and in e you get e.latLng object. But I have been getting empty latLng object. I have tried putting onClick event on myMapComponent as well as on Map component. This is what I get.

.Jm {latLng: _.N, ya: MouseEvent, pixel: _.K, qa: _.K}latLng: _.N {lat: ƒ, lng: ƒ}ya: MouseEvent {isTrusted: false, screenX: 91, screenY: 262, clientX: 91, clientY: 262, …}pixel: _.K {x: 75, y: 246}qa: _.K {x: 128.92420605694446, y: 88.34013104858127}__proto__: Object
latLng: _.N
lat: ƒ ()
lng: ƒ ()

Solution

  • Try e.latLng.lat() or e.latLng.lng() - notice the parenthesis.

    What I understand from your console is that lat, lng are getter functions not object properties - see this for more info.