代码之家  ›  专栏  ›  技术社区  ›  Philll_t Nowshath

谷歌地图如何获得标记位置?

  •  4
  • Philll_t Nowshath  · 技术社区  · 7 年前

    我阅读了这些文档,它很方便地概述了可用的道具和方法。请看 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 事件我想更新的状态 MyParentComponentWrapper 其中包含lat和lng,但我不知道如何调用 getPosition() 获取lat lng值。没有提供任何示例,文档看起来也不清楚。。。是否有方法调用 Marker 我不知道的组件?如果你知道如何做到这一点,你能提供一个如何做到这一点的例子吗?

    1 回复  |  直到 7 年前
        1
  •  4
  •   Vadim Gremyachev    7 年前

    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