Search code examples
reactjsgoogle-mapsgoogle-maps-react

Google Map API in React: How to assign InfoWindow for each Marker


I started my project with create-react-app, and installed google-maps-react.
Now I want to assign InfoWindow for each Marker, so I can show a lot of them at once. (maybe the answer is obvious, but not for me...)
My code:

export class MapContainer extends Component {
  render() {
    return (
      <Map
        className={'map'}
        google={this.props.google}
        zoom={13}
        initialCenter={{lat: 54.753986, lng: 24.670219}}
        style={nullStyle}
      >
        {this.props.places.map(place => (
          <Marker
            key={`marker-${place.name}`}
            title={place.title}
            name={place.name}
            position={place.position}
          />
        ))}
        {this.props.places.map(place => (
          <InfoWindow
            key={`infowindow-${place.name}`}
            marker={_JUST_BEFORE_CREATED_MARKER_}
            visible={true}>
            <div>{place.title}</div>
          </InfoWindow>
        ))}
      </Map>
    )
  }
}

Solution

  • To associate info window with a marker, render it inside a <Marker>, the below example demonstrates how to instantiate info window per every marker:

    <GoogleMap
        defaultZoom={5}
        defaultCenter={new google.maps.LatLng(-25.0317893, 115.219989)}>
    
        {props.places.map(place => (
            <Marker
                key={`marker-${place.name}`}
                title={place.title}
                name={place.name}
                position={place.position}
    
            >
                <InfoWindow
                    key={`infowindow-${place.name}`}
                    visible={true}>
                    <div>{place.title}</div>
                </InfoWindow>
            </Marker>
        ))}
    
    </GoogleMap>
    

    Demo