I'm using google-maps-react
to render an array with several polygons on a map.
When I click on a polygon, I would like it to return all the coordinates for that selected polygon. Can you tell me how I can do that?
Here is a picture of how I am rendering my coordinates on the map:
I would like something else too, if possible, to add a hover
event when I hover over each of the polygons. In the same way as this video I found on the internet: https://recordit.co/MciFGBL3b7
Here's my code I put at codesandbox: https://codesandbox.io/s/blissful-herschel-25rsl?file=/src/App.js
Thanks in advance.
I saw that you reduced your data.coordinates
json into auxCoords
. What you can do is to push it into an array, then use this array to map those paths from auxCoords to a <Polygon/>
. Here's how I achieved this:
import data from "./data.json";
const dataArray = [];
let auxCoords = {
auxCoords: data.coordinates.reduce(
(a, [c]) => a.concat([c.map(([lat, lng]) => ({ lat, lng }))]),
[]
)
};
dataArray.push(auxCoords.auxCoords[0]);
<Map/>
, you will see that I enclosed the <Polygon/>
in the {auxCoords.auxCoords.map((poly, key) => ()}
. This is mapping each polygon path arrays from the auxCoords. In this case, it individually creates a <Polygon/>
object which you can access the path and properties of each shape. Also, notice the onClick, onMouseover and onMouseout parameters
inside the <Polygon/>. Luckily, these events are supported by [
google-maps-react`](https://www.npmjs.com/package/google-maps-react#events-2). return (
<div>
<Map
className="map"
google={this.props.google}
onClick={this.onMapClicked}
initialCenter={{
lat: -47.7027099655629,
lng: -22.26485424139211
}}
style={{ height: "100%", position: "relative", width: "100%" }}
zoom={14}
>
{auxCoords.auxCoords.map((poly, key) => (
<Polygon
key={key}
paths={poly}
strokeColor="#0000FF"
strokeOpacity={0.8}
strokeWeight={2}
fillColor="#0000FF"
fillOpacity={0.35}
onClick={this.onPolyClick}
onMouseover={this.onPolyHover}
onMouseout={this.onPolyHoverOut}
/>
))}
</Map>
</div>
);
polygon
using the method getPaths
then used setOptions
to change the fillColor when you hover on an individual polygon. In the onPolyHoverOut, I changed back the fillColor to the original fillColor.onPolyClick = (props,polygon, e) => {
console.log("onclick:");
console.log(props.paths);
};
onPolyHover = (props, polygon, e) => {
console.log("onHover:");
console.log(polygon.getPaths());
polygon.setOptions({ fillColor: "#ff00ff" });
};
onPolyHoverOut = (props, polygon, e) => {
console.log("onHover:");
polygon.setOptions({ fillColor: "#0000FF" });
};
See this working code. Note: use your API key to make the code work.