Google maps 如何在google maps中调用函数getCenter()和其他函数
我试过:Google maps 如何在google maps中调用函数getCenter()和其他函数,google-maps,reactjs,Google Maps,Reactjs,我试过: <GoogleMap defaultZoom={14} center={{lat: props.mapCenter.lat, lng: props.mapCenter.lng}} onCenterChanged={getCenter()} /> 但我得到了一个错误: getCenter未定义 如何解决此问题,谢谢。您需要像这样使用它: onCenterChanged={this.getCenter} 注意:onCenterChanged是一个事件,因此请确保
<GoogleMap
defaultZoom={14}
center={{lat: props.mapCenter.lat, lng: props.mapCenter.lng}}
onCenterChanged={getCenter()}
/>
但我得到了一个错误:
getCenter未定义
如何解决此问题,谢谢。您需要像这样使用它:
onCenterChanged={this.getCenter}
注意:onCenterChanged
是一个事件,因此请确保在构造函数中定义了绑定,如下所示
this.getCenter = this.getCenter.bind(this);
或者您也可以通过箭头功能:
onCenterChanged={ (e)=> this.getCenter(e)}
更新:您没有提到您正在使用的是无状态功能组件
,每当询问问题时,请尝试提供完整信息
检查此项,如何在无状态功能组件中定义功能
:
const MarkerClustererExampleGoogleMap = withGoogleMap(props => (
<GoogleMap
defaultZoom={14}
center={{lat: props.mapCenter.lat, lng: props.mapCenter.lng}}
onCenterChanged={getCenter()}
>
)
var-App=()=>{
var click=function(){
console.log('a');
}
返回(
点击
)
}
ReactDOM.render(,document.getElementById('app'))
看看这个例子:。
这部分代码将向您显示正确的路径)
您可以通过Reactref
调用map组件,从map API调用函数,如getCenter()
、getZoom()
、getBounds()
等
这里是一个粗略的示例,请注意,这是一个未经测试的代码段,应该被视为伪代码,但希望它能让您了解如何进行此设置:
let ref
...
<GoogleMap
ref={(mapRef) => ref = mapRef} // bind the ref
onCenterChanged={() => {
ref.getCenter() // get the center, zoom, whatever using the ref
}}
/>
let ref
...
ref=mapRef}//绑定ref
onCenterChanged={()=>{
ref.getCenter()//使用ref
}}
/>
例如,文档中有更详细的示例说明如何执行此操作。哦,我可以像您的解决方案一样使用,但我有无状态组件。我的变量“this”没有定义。我使用不带变量“this”的组件GoogleMapconst MarkerClustererExampleGoogleMap=withGoogleMap(props=>(
@cm brain)检查更新的答案,如何在无状态功能组件中定义函数。以与工作相同的方式编写它。
let ref
...
<GoogleMap
ref={(mapRef) => ref = mapRef} // bind the ref
onCenterChanged={() => {
ref.getCenter() // get the center, zoom, whatever using the ref
}}
/>