Reputation: 3
I am currently working on an application that uses React Native Maps. I've seen their examples for putting multiple markers and how to change a marker's state when pressed, and I would like to be able to combine the two functions together. I want to be able to put down multiple markers, then change the state of individual markers when pressed. I've had success putting down multiple markers, but when pressed, all markers have their state changed. I'd like to know what to do so markers will have individual states changed when pressed. Thanks for all the help.
Here are the links to the examples of React Native Maps I used: https://github.com/airbnb/react-native-maps/blob/master/example/examples/DefaultMarkers.js
https://github.com/airbnb/react-native-maps/blob/master/example/examples/MarkerTypes.js
Here's the code I currently have
const SPACE = 0.01;
let id = 0;
class MarkerTypes extends React.Component {
constructor(props) {
super(props);
this.state = {
marker1: true,
region: {
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
},
markers: [],
};
}
onMapPress(e) {
console.log(e)
this.setState({
markers: [
...this.state.markers,
{
coordinate: e.nativeEvent.coordinate,
key: id++,
marker1: true,
},
],
});
}
render() {
return (
<View style={styles.container}>
<MapView
provider={this.props.provider}
style={styles.map}
initialRegion={this.state.region}
onPress={(e) => this.onMapPress(e)}
>
{this.state.markers.map(marker => (
<MapView.Marker
key={marker.key}
})}
onPress={() => {
this.setState({ marker1: !this.state.marker1 })}
}
coordinate={marker.coordinate}
image={this.state.marker1 ? flagBlueImg : flagPinkImg}
>
</MapView.Marker>
))}
</MapView>
</View>
);
}
}
Upvotes: 0
Views: 3762
Reputation: 944
To change the image marker on the marker that is touched on the map you need to toggle the marker property on the marker inside the this.state.markers array, eg this.state.markers[0].marker1, currently you are toggling the this.state.marker1 which is shared by all markers
{this.state.markers.map((marker, index) => (
<MapView.Marker
key={marker.key}
onPress={() => {
const marker = this.state.markers[index]
marker.marker1 = !marker.marker1
this.setState({ markers: [
...this.state.markers.slice(0, index),
marker,
...this.state.markers.slice(index + 1)
]})}
}
coordinate={marker.coordinate}
image={marker.marker1 ? flagBlueImg : flagPinkImg}
>
</MapView.Marker>
))}
in this way each marker is using and updating it's own state in the array.
Upvotes: 3