Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open callouts for React Native Maps markers upon loading

I want all the callouts for all the markers to be opened upon mounting the screen component. Currently, it only opens only when it's clicked on the marker. How do I use useRef in a functional component to do this?

const markerRef = useRef(React.createRef)

return (
    <View style={styles.container}>
        <MapView 
            style={{ flex: 1 }} 
            region={region}
            onRegionChangeComplete={onRegionChangeComplete}
        >
            {data && data.posts.map(marker => (
                <Marker
                    ref={markerRef}
                    key={marker.id}
                    coordinate={{latitude: marker.latitude, longitude: marker.longitude }}    
                >
                    <Callout>
                        <Text>{marker.title}</Text>
                        <Text>{JSON.stringify(marker.price)}</Text>
                    </Callout>
                </Marker>
            ))}
        </MapView>
        <View style={styles.inputContainer}> 
            <Icon name="magnify" size={30} color="lightgrey" />
            <TextInput 
                placeholder="Search Term"
                style={styles.input}
                onChangeText={setSearch}
                value={search}
                returnKeyType="search"
                onSubmitEditing={handleSubmit}
            />
        </View>
    </View>

When I console.log(markerRef.current), it doesn't provide the showCallout() method.

like image 480
Kevvv Avatar asked Jan 22 '26 18:01

Kevvv


1 Answers

I have done in this way

in parent component

<Marker_List_Start coordinate_start={Here I am passing coordinates and descriptions}/>

in child component

export default class Marker_List_Start extends Component {
  show = () => {
    this.marker2.showCallout();
  };

  hide = () => {
    this.marker2.hideCallout();
  };

 componentDidUpdate(previousProps,prevState){
if(previousProps.coordinate_start!=this.props.coordinate_start){
    this.hide()
}

 }

  render() {
    const {coordinate_start} = this.props;
    return (
      <>
        <Marker
          ref={ref => {
            this.marker2 = ref;
          }}
          coordinate={coordinate_start}
            //  title={coordinate_start.hole}
            //     description={coordinate_start.description}
          onPress={() => {
            this.show();
          }}>
          <Callout>
            <Text style={{fontWeight: 'bold', color: '#000'}}>
              {coordinate_start.description}
            </Text>
          </Callout>
        </Marker>
      </>
    );
  }
}
like image 80
Sayan Dey Avatar answered Jan 24 '26 13:01

Sayan Dey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!