使用 react-google-maps 从 google 地图获取 lat/lng

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

我有我的地图组件

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;

我的应用程序组件return此代码

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

我希望在用户点击地图时出现 lat/lng。我在每个答案中找到的最直接的方法是有 onClick 事件,并且在 e 中你得到 e.latLng 对象。但是我得到的是空的 latLng 对象。我试过将 onClick 事件放在 myMapComponent 和 Map 组件上。 这就是我得到的。

.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: ƒ ()

试试 e.latLng.lat()e.latLng.lng() - 注意括号。

我从您的控制台了解到,lat、lng 是 getter 函数而不是对象属性 - 请参阅 this 了解更多信息。