karl
karl

Reputation: 331

Multiple info windows in react-google-maps can't pass marker id

I have multiple markers on the map but each time I click a marker to get the info window all the markers info windows open!

I can see what the problem is, I was originally not telling it what window to load. I've tried passing it the index but this does not work for me.

This is what I have currently:

import React from "react";
const { compose, withProps, withStateHandlers } = require("recompose");
const {
    withScriptjs,
    withGoogleMap,
    GoogleMap,
    Marker,
    InfoWindow,
} = require("react-google-maps");

const MapsJson = compose(
  withProps({
    googleMapURL: "https://maps.googleapis.com/maps/api/js?key=&v=3.exp&libraries=geometry,drawing,places",
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: `400px` }} />,
    mapElement: <div style={{ height: `100%` }} />,
  }),
  withStateHandlers(() => ({
    isOpen: false,
  }), {
    onToggleOpen: ({ isOpen }) => () => ({
      isOpen: !isOpen,
    })
  }),
  withScriptjs,
  withGoogleMap
)(props =>
  <GoogleMap
    defaultZoom={6}
    defaultCenter={{ lat: parseFloat(props.setLat, 10), lng: 
parseFloat(props.setLng, 10) }}
  >

      {props.markers.map((marker, index)=> {
        let lat = parseFloat(marker.location.latitude, 10);
        let lng = parseFloat(marker.location.longitude, 10)
        //console.log(index);
        return (
          <Marker
            id = {index}
            key={index}
            position={{ lat: lat, lng: lng }}
            title="Click to zoom"
            onClick={() => { props.onToggleOpen({index}); }}
            >
          {props.isOpen[{index}] && 

                  <InfoWindow onCloseClick={props.onToggleOpen({index})}>
                    <div>
                       {marker.category}
                    </div>
                  </InfoWindow>
              }
          </Marker>
          )
        }
      )}
  </GoogleMap>
);

export default MapsJson;

Upvotes: 0

Views: 1407

Answers (1)

Rebecca Tay
Rebecca Tay

Reputation: 331

State isOpen doesn't seem to be an array. It toggles between true/false values. Could you check what props.isOpen[{index}] is evaluating to? If all markers open then it might be perpetually truthy.

Another way of doing this might be to store the index of the clicked marker in state. eg. clickedMarkerIndex = x. Then,

{props.markers.map((marker, index) => {
  return (
    <Marker onClick={() => this.handleMarkerClick(index)}>
      {clickedMarkerIndex === index &&
        <InfoWindow />
      }
    </Marker>
  )
})

Upvotes: 2

Related Questions