【问题标题】:Use react-google-maps methods with recompose将 react-google-maps 方法与 recompose 一起使用
【发布时间】:2019-02-04 16:33:45
【问题描述】:

我正在使用 react google maps 在地理定位功能后微调用户位置,这是我的 Map.js 代码的一部分:

    const MyMapComponent = compose(
  withProps({
    googleMapURL: "https://maps.googleapis.com/maps/api/js?key=AIzaSyAKCqAqiyop85LNl9qUb6OAT1lJupLEnzo&v=3.exp&libraries=geometry,drawing,places",
    loadingElement: <div style={{height: `100%`}}/>,
    containerElement: <div style={{height: `400px`}}/>,
    mapElement: <div style={{height: `100%`}}/>,
  }),
  withState(),
  withHandlers(() => {
    const refs = {
      map: undefined,
    }

    return {
      onMapMounted: () => ref => {
        refs.map = ref
      },
      onBoundsChanged: ({onBoundsChanged}) => () => {
        onBoundsChanged(refs.map.getCenter().lat(), refs.map.getCenter().lng())
      }
    }
  }),
  withScriptjs,
  withGoogleMap
)((props) =>
  <GoogleMap
    defaultZoom={8}
    defaultCenter={{lat: props.lat, lng: props.lng}}
    ref={props.onMapMounted}
    onBoundsChanged={props.onBoundsChanged}
  >
    <Marker position={{lat: props.lat, lng: props.lng}}/>
  </GoogleMap>
)

我只是希望能够通过 ref 调用其他组件中的 panTo() 方法,在内部我没有问题,因为我认为 ref 在 mapMounted 方法(refs.map.getCenter().lat() ),但是如何在外部调用你的方法,我的问题是我使用 recompose 库。提前谢谢。

Home.js 中的部分代码,我使用 map 并拥有我想要触发 panTo() 的 get position 方法:

import MyMapComponent from './Maps';
export default class HomeComponent extends React.Component {

render() {
 const {showAlert, address, lat, lng} = this.props;
 return (
          <MyMapComponent
            lat={lat}
            lng={lng}
            onBoundsChanged={this.props.handleOnBoundsChanged}
          />
          <Button onClick={()=>this.props.getPosition()}>Usar mi 
                   ubicación actual</Button>
        )
    }
  }

【问题讨论】:

  • 您仍然可以将计算的 prop 传递给 GoogleMap,然后在任何事件处理程序中将其与 panTo 一起使用
  • 我是 React 的新手,如果您能提供帮助,我正在努力研究如何制作事件处理程序并调用它。我有一个代码示例我会非常感谢你
  • 听着,你能告诉我你想什么时候调用 panTo () 吗?用例是什么
  • 我使用 getGeolocation 函数,然后在地图中绘制一个标记,因此之后我想将地图平移到 getGeolocation 函数获得的新位置,所以基本上我需要一种调用该函数的方法使用新的 lat lng 参数,希望我能解释一下,并提前感谢您的时间@sak
  • 您的 getCurrentLocation 处理程序在哪里?

标签: reactjs react-google-maps recompose


【解决方案1】:

您可以使用任何地图方法创建道具。

...

withHandlers(() => {
  let map;
  return {
    onMapMounted: () => ref => {
      map = ref;
    },

    onBoundsChanged: ({ onBoundsChanged }) => () => {
      onBoundsChanged(map.getCenter().lat(), map.getCenter().lng());
    }

    mapPanTo: () => args => map.panTo(args),
  };
})

...

现在props.mapPanTo 可以传递给任何其他组件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-30
    • 2013-04-09
    • 2020-06-13
    • 2016-11-06
    • 2018-02-19
    • 1970-01-01
    • 2017-03-27
    • 2015-03-06
    相关资源
    最近更新 更多