使用react-google-maps从谷歌地图获取经纬度

4
我有一个地图组件。
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 (
      <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>
    );

当用户点击地图时,我希望能够获得经纬度。在所有答案中,我发现最直接的方法是使用onClick事件,并在事件中获取e.latLng对象。但是我一直收到一个空的latLng对象。我已经尝试在myMapComponent和Map组件上都放置onClick事件。

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

我已经从您的问题中删除了API密钥。请不要在公共网站上分享私人API密钥,并确保按照https://developers.google.com/maps/api-key-best-practices#restrict_apikey进行限制。 - Pagemag
1个回答

5
尝试使用e.latLng.lat()e.latLng.lng(),注意括号的使用。
从您的控制台输出可以看出,lat和lng是获取函数,而不是对象属性 - 有关更多信息,请参见此链接

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接