Q: react-native-maps: how to use marker.showCallout() for an array of coordinates mapped as markers

允我心安 提交于 2019-12-07 23:33:07

问题


I'm currently fiddling around with react-native-maps to simulate various moving objects around a map space (simulating real time tracking of items) with a callout showing each object's name beside the marker denoting it.

I'm currently able to show the callout for each marker whenever I press it. However, what I intend to do is create a button which toggles on or off the callouts for every marker on the map.

I'm currently using the react-native-maps library for my map.

What I've done are as such:

/* 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();
  }
}

It seems that when I render a single Marker component, this method works. However, I can't quite crack my head to get around using showCallout() to show the callouts for an entire group of markers.

Would anyone be able to shed some light on how to go about doing this?


回答1:


1. Wrap the component MapView.Marker into a custom Marker:

class Marker extends React.Component {
  marker

  render () {
    return (
      <MapView.Marker {...this.props} ref={_marker => {this.marker = _marker}} />
    )
  }

  componentDidUpdate () {
    this.updateCallout()
  }

  updateCallout () {
    if (this.props.calloutVisible) {
      this.marker.showCallout()
    } else {
      this.marker.hideCallout()
    }
  }
}

2. Update your higher level component accordingly in order to provide the callout visibility filter via 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>
))}


来源:https://stackoverflow.com/questions/41870405/q-react-native-maps-how-to-use-marker-showcallout-for-an-array-of-coordinate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!