react-google-maps 如何获取标记位置?

Phi*_*l_t 4 ecmascript-6 reactjs react-google-maps

我阅读了文档,它方便地概述了可用的道具和方法。请看这里

我的问题是,给出这里的示例组件:

import {withScriptjs, withGoogleMap, GoogleMap, Marker} from "react-google-maps";

class MyParentComponentWrapper extends Component { 
...

...// inside react component class
mapComponent() {
        const MyMapComponent = withScriptjs(withGoogleMap((props) =>{
            return (
                <GoogleMap
                    defaultZoom={18}
                    defaultCenter={{ lat: props.lat, lng: props.lng }}
                >
                    { props.isMarkerShown && <Marker onPositionChanged={()=>{
// This event will trigger the 
// call to update the state where lat and lng will go.

}} draggable position={{ lat: props.lat, lng: props.lng }} /> }
                </GoogleMap>
            )
        }))

        return (
            <MyMapComponent
                lat={this.state.form.location.latitude}
                lng={this.state.form.location.longitude}
                googleMapURL={`https://maps.googleapis.com/maps/api/js?key=${env.google.apiKey}&v=3.exp&libraries=geometry,drawing,places`}
                loadingElement={<div style={{ height: `100%` }} />}
                containerElement={<div style={{ height: `400px` }} />}
                mapElement={<div style={{ height: `100%` }} />}
                isMarkerShown/>
        )
    }

...
Run Code Online (Sandbox Code Playgroud)

看到onPositionChanged活动了吗?我想更新包含MyParentComponentWrapperlat 和 lng 的状态,但我不知道如何调用getPosition()来获取 lat lng 值来执行此操作。没有提供示例,文档看起来不清楚...有没有办法调用Marker我不知道的组件内的方法?如果您知道如何执行此操作,能否提供一个示例来说明如何执行此操作?

Vad*_*hev 6

onPositionChangedevent 不提供触发事件,但您可以Marker通过ref属性存储对组件的引用:

<GoogleMap defaultZoom={8} defaultCenter={{ lat: -34.397, lng: 150.644 }}>
        <Marker position={{ lat: -34.397, lng: 150.644 }} draggable={true} ref={props.onMarkerMounted} onPositionChanged={props.onPositionChanged} />    
</GoogleMap>   
Run Code Online (Sandbox Code Playgroud)

然后获取onPositionChanged事件中标记的位置,如下所示:

lifecycle({
    componentWillMount() {
        const refs = {}

        this.setState({

            onMarkerMounted: ref => {
                refs.marker = ref;
            },

            onPositionChanged: () => {
                const position = refs.marker.getPosition();
                console.log(position.toString());
            }
        })
    },
}) 
Run Code Online (Sandbox Code Playgroud)

演示