Ad

How To Have Google Maps Markers In Different Colors In React Native?

- 1 answer

I want the marker with id: 0 to be red and the marker with id: 1 to be green, but currently both markers are the same color, either red or green depending on icon in Marker. Does anyone have any advice?

constructor(props) {
  super(props);
  this.state = {
    coordinates: [
      {id: 0, latitude: 37.789086, longitude: -122.432216},
      {id: 1, latitude: 37.787217, longitude: -122.431830}
    ],
    redMarker: require('./markers/red.png'),
    greenMarker: require('./markers/green.png')
  }
}
<MapView>
  {this.state.coordinates.map((marker, index) => (
    <Marker
      key = {index}
      tracksViewChanges = {false}
      coordinate = {{
        latitude: marker.latitude, 
        longitude: marker.longitude
      }}
      icon = {this.state.greenMarker}>
    </Marker>
  ))}
</MapView>
Ad

Answer

Just use the modulo operator:

icon = {index % 2 === 0 ? this.state.greenMarker : this.state.redMarker}>
Ad
source: stackoverflow.com
Ad