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

时间:2018-02-02 17:51:18

标签: reactjs ecmascript-6 react-google-maps

我阅读了文档,并方便地概述了可用的道具和方法。请查看here

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

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/>
        )
    }

...

查看onPositionChanged活动?我想更新包含lat和lng的MyParentComponentWrapper状态,但我不知道如何调用getPosition()来获取lat lng值。没有提供示例,文档看起来不清楚......有没有办法在Marker组件中调用我不知道的方法?如果您知道如何操作,请提供一个如何操作的示例吗?

1 个答案:

答案 0 :(得分:3)

onPositionChanged事件未提供触发事件,但您可以通过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>   

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

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

        this.setState({

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

            onPositionChanged: () => {
                const position = refs.marker.getPosition();
                console.log(position.toString());
            }
        })
    },
}) 

Demo