Mats
Mats

Reputation: 165

Changing color of selected polygon on google-maps-react

I'm using google-maps-react and trying to change the color of an overlaid polygon as it's selected. The polygons are also part of the google-maps-react.

The polygons accept a new selected state, and the setColor function even returns the correct color. It just doesn't change on the map itself.

Code is as follows:

setColor = (selected, index) => {
      if (selected) {
          return "blue" //Even when blue is returned, no color change is visible
      } else {
          return "red"
      }
  }



render() {
    return (
        <Polygon
          paths={this.props.paths}
          onClick={() => this.handleClick()}
          strokeColor="#2A2A57"
          strokeOpacity={0.8}
          strokeWeight={2} 
          fillColor = {this.setColor(this.state.isSelected, this.state.index)}
          fillOpacity={0.35}
          {...this.props}
        />
      )
    }

Upvotes: 2

Views: 4601

Answers (2)

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59338

It appears it is by google-maps-react library design, only changing paths props causes Polygon to re-render.

The following approach could be considered to update Polygon properties (e.g, fillColor):

1) Get the instance of Google Maps Polygon object via ref attribute:

 <Polygon
          ref={this.polygonRef}
          onClick={this.handleClick}
          paths={triangleCoords}
 />

2) Update polygon properties via Polygon.setOptions function:

handleClick = e =>{
   this.setPolygonOptions({fillColor: "green"});
}

where

setPolygonOptions = (options) => {
   this.polygonRef.current.polygon.setOptions(options);
};

Demo

Update

Another option would be to access Polygon instance and modify its properties as demonstrated below. Once the polygon object is clicked, its instance is passed via the second parameter of click event:

handleClick = (props,polygon,e) => {
    polygon.setOptions({ fillColor: "#ff00ff"});
};

Demo 2

Upvotes: 3

Chris Hawkes
Chris Hawkes

Reputation: 12410

Do this...

  <Polygon
      paths={this.props.paths}
      onClick={() => this.handleClick()}
      options={{ strokeOpacity: 0.8, strokeColor: "#2A2A57", fillColor:"#000"}}
      {...this.props}
    />

You want to pass the styling options to the Google Maps API via the prop.options.

Upvotes: 2

Related Questions