How Do I Return The Coordinates Of My Selected Polygon?
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. C
Solution 1:
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:
- Pushing the reduced json data in an array
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]);
- Inside the
<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 theonClick, 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><MapclassName="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) => (
<Polygonkey={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>
);
- Then here are the functions that I called in the above events. In the onClick, I get the path using the props. In the onPolyHover, I get the path from
polygon
using the methodgetPaths
then usedsetOptions
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.
Post a Comment for "How Do I Return The Coordinates Of My Selected Polygon?"