React-Google-Map multiple Info window open
Asked Answered
V

1

6

I am currently building a google map api using react-google-maps and I would like to create multiple markers to display info of cities around the world on the info window. But since they are all from the html object. Whenever I clicked on one marker, all info windows will be opened. If there a way to fix this? Sample code:

<GoogleMap
    defaultZoom={3}
    defaultCenter={{ lat: 40.452906, lng: 190.818206 }}
  >
    <Marker id = "mark1"
      options={{icon: Mark1}} 
      position={{ lat: 34.4076645, lng: 108.742099 }}
      onClick={props.onToggleOpen}
    >
      {props.isOpen && <InfoWindow id = "info1"
                    onCloseClick={props.onToggleOpen}
                    >
                    <div> content1 </div>
      </InfoWindow>}
    </Marker>
    <Marker
      options={{icon: Mark2}} 
      position={{ lat: 35.6958783, lng: 139.6869534 }}
      onClick={props.onToggleOpen}
    >
      {props.isOpen && <InfoWindow
                    onCloseClick={props.onToggleOpen}
                    >
                    <div> content2 </div>
      </InfoWindow>}
    </Marker>
</GoogleMap>
Veronique answered 25/10, 2017 at 15:46 Comment(2)
Just bind each info marker separately to the mapMisconceive
did you solve your issue ? can u provide us a solution ?Premillennialism
M
1

In your code, onClick of Marker you just call {props.onToggleOpen}, which i hope toggles a flag. Here you should send which marker you are clicking so you need to modify your onClick to something like below

onClick={() => { props.onToggleOpen("mark1"); }}

In the above line, Mark1 should be a unique value that you can use to identify the respective Marker. You can replace this with the marker id or of something that will be unique to the respective Marker.

Second, you need to modify onToggleOpen to toggle the flag for the respective marker which is identified by the argument it receives(the unique value you send from `onClick). You can use an array like data structure to store this value.

Then you need to show your InfoWindow based on the flag respective to the Marker. Considering isOpen will be an array of flags(after incorporating the above changes), one would show InfoWindow using condition something like below

<Marker id = "mark1"
  options={{icon: Mark1}} 
  position={{ lat: 34.4076645, lng: 108.742099 }}
  onClick={() => { props.onToggleOpen("mark1"); }}
>
  {props.isOpen["mark1"] && <InfoWindow id = "info1"
                onCloseClick={() => { props.onToggleOpen("mark1"); }}
                >
                <div> content1 </div>
  </InfoWindow>}
</Marker>

Hope that leads you to a right direction.

Milden answered 25/10, 2017 at 16:10 Comment(1)
Could you please post an example of how you solved this @Veronique ?Diaphone

© 2022 - 2024 — McMap. All rights reserved.