我有一个使用 https://github.com/tomchentw/react-google-maps 的非常简单的 React 应用程序但我很难理解如何获取对当前 map 的引用或如何访问自定义组件中的 google.maps.Map
对象。
我找到了 this在 repo 协议(protocol)上,但在阅读了帖子后,我仍然有点困惑。
我开始使用 DirectionsRenderer 构建我的应用程序示例。
我接下来要做的是添加我自己的自定义组件,用于选择起点和使用 Google Maps 自动完成 API。
Yes, I know that the package has a component for that already, but I need to do a little more than just search for a location on the map.
为了完成我的需求,我会做类似的事情
const autocomplete = new google.maps.places.Autocomplete(node);
autocomplete.bindTo('bounds', map);
node
是我绑定(bind)自动完成功能的元素,map
是 google.maps.Map
对象的一个实例。
到目前为止我的申请:
App.jsx
const App = ({ store }) => (
<Provider store={store}>
<div>
<Sidebar>
<StartingPoint defaultText="Choose starting point…" />
</Sidebar>
<GoogleApiWrapper />
</div>
</Provider>
);
GoogleApiWrapper
const GoogleMapHOC = compose(
withProps({
googleMapURL: 'https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places&key=__GAPI_KEY',
loadingElement: <div style={{ height: '100vw' }} />,
containerElement: <div style={{ height: '100vh' }} />,
mapElement: <div style={{ height: '100%' }} />,
}),
withScriptjs,
withGoogleMap,
lifecycle({
componentDidMount() {
const DirectionsService = new google.maps.DirectionsService();
// make google object available to other components
this.props.onLoad(google);
DirectionsService.route({
origin: new google.maps.LatLng(41.8507300, -87.6512600),
destination: new google.maps.LatLng(41.8525800, -87.6514100),
travelMode: google.maps.TravelMode.DRIVING,
}, (result, status) => {
if (status === google.maps.DirectionsStatus.OK) {
this.setState({
directions: result,
});
} else {
console.error(`error fetching directions ${result}`);
}
});
},
}),
)(props => (
<GoogleMap
ref={props.onMapMounted}
defaultZoom={13}
defaultCenter={new google.maps.LatLng(37.771336, -122.446615)}
>
{props.directions && <DirectionsRenderer directions={props.directions} />}
</GoogleMap>
));
如果我无法访问包装器外部的 google.maps.Map
对象,我还想访问对包含 map 的元素的引用,以便实例化一个 new google.maps.Map(ref_to_elem, options);
如有任何帮助,我们将不胜感激!
最佳答案
你可以通过 React refs 做到这一点:
<GoogleMap ref={(map) => this._map = map} />
function someFunc () {
//using, for example as:
this._map.getCenter()
this._map.setZoom(your desired zoom);
}
关于javascript - 如何使用 react-google-maps 访问 google.maps.Map 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46268604/