我阅读了文档,并方便地概述了可用的道具和方法。请查看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
组件中调用我不知道的方法?如果您知道如何操作,请提供一个如何操作的示例吗?
答案 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());
}
})
},
})