Search code examples
javascriptreactjsgoogle-mapsgoogle-maps-react

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}
        />
      )
    }

Solution

  • 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