【问题标题】:Q: react-native-maps: how to use marker.showCallout() for an array of coordinates mapped as markers问:react-native-maps:如何将 marker.showCallout() 用于映射为标记的坐标数组
【发布时间】:2017-01-26 09:32:23
【问题描述】:

我目前正在摆弄 react-native-maps 来模拟地图空间周围的各种移动对象(模拟项目的实时跟踪),并在标记旁边显示每个对象的名称的标注。

我目前能够在按下每个标记时显示它的标注。但是,我打算创建一个按钮,用于打开或关闭地图上 每个 标记的标注。

我目前正在为我的地图使用 react-native-maps 库。

我所做的是这样的:

/* this.props.trackedObjects is an array of objects containing
coordinate information retrieved from database with the following format
  
  trackedObjects=[{
    coordinate:{
      latitude,
      longitude
    },
    userName
  }, ...]
  
*/

/* inside render() */

{this.props.trackedObjects.map((eachObject) => (
  <View>
    <MapView.Marker
      ref={ref => {this.marker = ref;}}
      key={eachObject.userName}
      coordinate={eachObject.coordinate}
    >
      /*Custom Callout that displays eachObject.userName as a <Text>*/
    </MapView.Marker>
  </View>
))}

/* Button onPress method */
onPress(){
  if(toggledOn){
    this.marker.showCallout();
  }else{
    this.marker.hideCallout();
  }
}

似乎当我渲染单个 Marker 组件时,此方法有效。但是,我无法完全摆脱使用 showCallout() 来显示整组标记的标注。

有没有人能够阐明如何去做这件事?

【问题讨论】:

    标签: android react-native react-native-maps


    【解决方案1】:

    1.将组件MapView.Marker包装成自定义Marker

    class Marker extends React.Component {
      marker
    
      render () {
        return (
          <MapView.Marker {...this.props} ref={_marker => {this.marker = _marker}} />
        )
      }
    
      componentDidUpdate (prevProps) {
         
         if (prevProps.calloutVisible !== this.props.calloutVisible) {
            this.updateCallout();
        }
      }
    
      updateCallout () {
        if (this.props.calloutVisible) {
          this.marker.showCallout()
        } else {
          this.marker.hideCallout()
        }
      }
    }
    

    2. 相应地更新您的更高级别的组件,以便通过 prop calloutVisible 提供标注可见性过滤器:

    /* inside render() */
    
    {this.props.trackedObjects.map((eachObject) => (
      <View>
        <Marker
          key={eachObject.userName}
          coordinate={eachObject.coordinate}
          calloutVisible={eachObject.calloutVisible} // visibility filter here
        >
          /*Custom Callout that displays eachObject.userName as a <Text>*/
        </MapView.Marker>
      </View>
    ))}
    

    【讨论】:

    • 我尝试了您的解决方案,它有效,但标注屏幕的大小与我定义的不同。
    猜你喜欢
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多