如何返回所选多边形的坐标?

泰娜拉

我正在使用google-maps-react在地图上渲染具有多个多边形的数组。

当我单击一个多边形时,我希望它返回该选定多边形的所有坐标。你能告诉我怎么做吗?

这是我如何在地图上渲染坐标的图片:

在此处输入图片说明

如果可能的话,我还想要其他的东西,hover当我将鼠标悬停在每个多边形上时添加一个事件。就像我在互联网上找到的这个视频一样:https : //recordit.co/MciFGBL3b7

这是我放在 codeandbox 中的代码:https ://codesandbox.io/s/blissful-herschel-25rsl ? file =/ src/App.js

提前致谢。

页码

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:

  1. 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]);
  1. 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 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>
    );
  1. 然后这里是我在上述事件中调用的函数。在 onClick 中,我使用道具获取路径。在 onPolyHover 中,当您将鼠标悬停在单个多边形上时,我polygon使用该方法获取路径,getPaths然后用于setOptions更改 fillColor。在 onPolyHoverOut 中,我将 fillColor 改回原来的 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" });
  };

请参阅此工作代码注意:使用您的 API 密钥使代码工作。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章