如何使用 React Google Maps API 访问 Map 对象?

How do I access a Map object using React Google Maps API?

我正在尝试使用新的 @react-google-maps/api library, which is a replacement for the unsupported react-google-maps library by tomchentw.

访问安装在我的 Web 应用程序中的 Google 地图的 getBounds 方法

与旧的 react-google-maps 不同,这个新库似乎无法访问 Google Map 对象 as defined here. 取决于您尝试访问的方式一个 Google 地图对象,你会得到以下两种情况之一:

1) 只需在标签内放置一个 ref 即可得到一个 GoogleMap 对象,它不是 Map 对象并且没有 getBounds 方法或任何其他允许我检索范围的方法地图(据我所知)。它的子对象之一是下面描述的 "Zh" 对象。

2) 在第 1 点的引用上调用 getInstance() 会得到一个神秘的、未记录的 "Zh" 对象,其中包含神秘的数据分类。此对象也作为 GoogleMap 的子项存在。

它们在控制台中:https://i.imgur.com/kGCToGv.jpg

这是生成该控制台输出的代码(我在应用程序中拖动地图后使用 onDragEnd 回调 运行 一些打印,因为在存储完成后试图立即读取地图的内容代码因某种竞争条件而跳闸):

import React from 'react'
import { LoadScript, GoogleMap, Marker } from '@react-google-maps/api'

function NewMap(props){

    let mapRef = React.createRef()

    const boundsCallBack = () => {
        console.log(mapRef.current)
        console.log(mapRef.current.getInstance())
    }

    return (
        <LoadScript googleMapsApiKey={process.env.REACT_APP_MAP_KEY}>
            <GoogleMap
                {...props.theProps}
                onDragEnd={boundsCallBack}
                ref={mapRef}
            >
                <Marker position={props.theProps.center} />
            </GoogleMap>
        </LoadScript>
    )
}

export default NewMap

GoogleMap 和 Zh 似乎都没有提供任何方法来访问实际的 Map 对象或任何返回其重要统计信息(例如其边界)的方法。有谁知道如何使用此库访问地图对象 and/or 其重要统计数据?

您可以从 onLoad 事件处理程序中获取它,并将地图对象放入您的状态,然后像这样在任何您想要的地方使用它:

import React, {Component} from 'react'
import { LoadScript, GoogleMap, Marker } from '@react-google-maps/api'

class NewMap extends Component {

    state = {map: {}}

    boundsCallBack = () => {
        const {map} = this.state;
        console.log('map: ', map)
    }

    handleMapLoad = (map) => {
        this.setState((state) => ({ ...state, map }));
    }

    render () {
      return (
        <LoadScript googleMapsApiKey={process.env.REACT_APP_MAP_KEY}>
            <GoogleMap
                {...this.props.theProps}
                onDragEnd={this.boundsCallBack}
                onLoad={this.handleMapLoad}
            >
                <Marker position={this.props.theProps.center} />
            </GoogleMap>
        </LoadScript>
      )
    }
}

export default NewMap