[英]How do I return the coordinates of my selected polygon?
我正在使用google-maps-react
在google-maps-react
上渲染一個包含多個多邊形的數組。
當我單擊一個多邊形時,我希望它返回該選定多邊形的所有坐標。 你能告訴我怎么做嗎?
這是我如何在地圖上渲染坐標的圖片:
如果可能的話,我還想要其他的東西,當我將鼠標懸停在每個多邊形上時添加一個hover
事件。 就像我在互聯網上找到的這個視頻一樣: https : //recordit.co/MciFGBL3b7
這是我放在 codeandbox 中的代碼: https ://codesandbox.io/s/blissful-herschel-25rsl ? file =/ src/App.js
提前致謝。
我看到您將data.coordinates
json 縮減為auxCoords
。 您可以做的是將其推入一個數組,然后使用該數組將這些路徑從 auxCoords 映射到<Polygon/>
。 這是我實現這一目標的方法:
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/>
,您將看到我將<Polygon/>
在{auxCoords.auxCoords.map((poly, key) => ()}
。這是從 auxCoords 映射每個多邊形路徑數組。在在這種情況下,它會單獨創建一個<Polygon/>
對象,您可以訪問每個形狀的路徑和屬性。另外,請注意<Polygon/>. Luckily, these events are supported by [
的onClick, onMouseover and onMouseout parameters
<Polygon/>. Luckily, these events are supported by [
google <Polygon/>. Luckily, these events are supported by [
-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>
);
getPaths
方法從polygon
獲取路徑,然后當您將鼠標懸停在單個多邊形上時使用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 密鑰使代碼工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.