Home > Enterprise >  React Native Map clickable Markers with props on IOS
React Native Map clickable Markers with props on IOS

Time:01-04

Hey I tried to build a Map with Markers on it, if you click the Marker a Carousel shod open with the Challenges.

onMarkerPressed(){
  navigation.navigate('ChallengeScreen');
}
  render(){
    const {latitude, longitude, onl oading,markers } = this.state;
        return(
          <View style={styles.container}>
            <MapView
            style={styles.mapview}
            loadingEnabled={true}
            region={{
                latitude: 49.4459,//latitude,
                longitude: 7.77151, //longitude,
                latitudeDelta: 0.00722,
                longitudeDelta: 0.00421
            }}
            > 
            {markers.map( marker => {
                return(
                    <MapView.Marker
                    key={marker.id}
                    coordinate={{
                        latitude: marker.latitude,
                        longitude: marker.longitude,
                    }}
                    onPress={this.onMarkerPressed}
                    >
                    </MapView.Marker>
                )
            })}
        </MapView>
        </View>
        )
    }
  }
}

But the OnPress only works with no props.... How can I get the clicked Marker as Prop in onMarkerPressed ?

CodePudding user response:

onMarkerPressed should receive pressed marker object keys-values pair properties and pass down to navigation.navigate('ChallengeScreen') as route parameters.

onMarkerPressed = (marker)=> {

const params = {marker}
  navigation.navigate('ChallengeScreen',params);
}
  render(){
    const {latitude, longitude, onl oading,markers } = this.state;
        return(
          <View style={styles.container}>
            <MapView
            style={styles.mapview}
            loadingEnabled={true}
            region={{
                latitude: 49.4459,//latitude,
                longitude: 7.77151, //longitude,
                latitudeDelta: 0.00722,
                longitudeDelta: 0.00421
            }}
            > 
            {markers.map(marker => {
                return(
                    <MapView.Marker
                    key={marker.id}
                    coordinate={{
                        latitude: marker.latitude,
                        longitude: marker.longitude,
                    }}
                    onPress={()=>this.onMarkerPressed(marker)}
                    >
                    </MapView.Marker>
                )
            })}
        </MapView>
        </View>
        )
    }
  }


Note: onMarkerPressed changed to arrow function to avoid function binding with component class.

Check React Navigation passing parameters to routes for in-depht guide.

  • Related