-1

I have predefined paths (array of arrays) to use in Polygon Component

  1. First I need a way to inject an id for the Polygon component and to get that id when mouseover & mouseout
  2. I need to change the options when mouseover, setOptions?
          options={{
            strokeColor: "#113460",
            strokeOpacity: 0.5,
            strokeWeight: 0.3,
            fillOpacity: 0.5,
            fillColor: "#199ee0"
          }}
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
JOOBOO
  • 69
  • 1
  • 6

1 Answers1

0

At least two options could be considered:

Option 1

Manage polygon options via React state, the following example demonstrates how to change polygon fillColor on mouseOver event:

const triangleCoords = [
  { lat: 25.774, lng: -80.19 },
  { lat: 18.466, lng: -66.118 },
  { lat: 32.321, lng: -64.757 },
  { lat: 25.774, lng: -80.19 }
];

function Map(props) {
  const { zoom, center } = props;


  const [polygonOptions, setPolygonOptions] = useState({
    strokeColor: "#FF0000",
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: "#FF0000",
    fillOpacity: 0.35,
    polygonKey: 1
  });

  function handleMouseOver(e) {
    setPolygonOptions({fillColor: "#FFFF00"});
  }



  return (
    <GoogleMap defaultZoom={zoom} defaultCenter={center}>
      <Polygon
        onMouseOver={handleMouseOver}
        path={triangleCoords}
        editable={true}
        options={polygonOptions}
      />
    </GoogleMap>
  );
}

Option 2

Access native Google Maps Polygon object, the following example demonstrates how to change fillColor on mouseOver event via Polygon.setOptions method:

function Map(props) {
  function handleMouseOver(e) {
    this.setOptions({ fillColor: "#FFFF00" });
  }

  const { zoom, center } = props;
  return (
    <GoogleMap defaultZoom={zoom} defaultCenter={center}>
      <Polygon
        onMouseOver={handleMouseOver}
        path={triangleCoords}
        key={1}
        editable={true}
        options={{
          strokeColor: "#FF0000",
          strokeOpacity: 0.8,
          strokeWeight: 2,
          fillColor: "#FF0000",
          fillOpacity: 0.35
        }}
      />
    </GoogleMap>
  );
}
Vadim Gremyachev
  • 57,952
  • 20
  • 129
  • 193
  • 1
    Super I can change my options but still can't get the id of the selected polygon, is there a way ? – JOOBOO Sep 15 '19 at 12:07
  • @JOOBOO regarding identifying the selected polygon, in **option 1** polygon identifier could be passed along with properties (see `polygonKey` in the provided example) in **option 2** the polygon is accessible via `this` context, for example: `this.setOptions({ fillColor: "#FFFF00" });` where this refer yo current polygon – Vadim Gremyachev Sep 15 '19 at 12:13
  • I am using option 2 & applying the key inside the polygon but unfortunately, I can't access the key through 'this' How can I reach key attribute inside this – JOOBOO Sep 17 '19 at 08:55