react-google-maps how does one get marker position?

这一生的挚爱 提交于 2019-12-07 12:21:09

问题


I read the docs and it conveniently outlines the props and methods available. Please look here.

My question is, given the example component 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/>
        )
    }

...

See the onPositionChanged event? I want to update the state of MyParentComponentWrapper which contains lat and lng, but I have no idea how to call the getPosition() to get the lat lng values to do so. No examples were provided and the documentation looks unclear... Is there a way to call the methods within the Marker component that I am unaware of? If you know how to do this, can you please provide an example on how to do so?


回答1:


onPositionChanged event does not provide the triggered event but you could store a reference to Marker component via ref attribute:

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

and then get the position of marker in onPositionChanged event like this:

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

        this.setState({

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

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

Demo



来源:https://stackoverflow.com/questions/48588302/react-google-maps-how-does-one-get-marker-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!