从多边形获取GeoJSON



我正在构建一个ReactJS应用程序,该应用程序允许用户使用带纬度和经度的坐标数组定义地图中的绘图。我想返回用户单击的多边形的GeoJSON。

我在文档中找不到当我们有多个数组时如何返回坐标数据。

正如我所做的,它总是返回带有所有坐标的数组。而不仅仅是单击的多边形的坐标。

我把我的代码放在CodeSandBox 中

以下是来自API的模拟数据

{
"coordinates": [
[
[
[25.774, -80.19],
[18.466, -66.118],
[32.321, -64.757],
[25.774, -80.19]
]
],
[
[
[25.774, -50.32],
[18.466, -36.118],
[32.321, -34.757],
[25.774, -50.32]
]
]
]
}

我的点击事件功能:

handleClick = (props, polygon, e) => {
let geoJSON = {
type: "Polygon",
coordinates: []
};
const paths = polygon.getPaths().getArray();
for (let path of paths) {
let pathArray = [];
let points = path.getArray();
let firstPoint = false;
for (let point of points) {
if (firstPoint === false) {
firstPoint = point;
}
pathArray.push([point.lng(), point.lat()]);
}
pathArray.push([firstPoint.lng(), firstPoint.lat()]);
geoJSON.coordinates.push(pathArray);
}
console.log("geoJSON", geoJSON);
return geoJSON;
};

您需要将坐标状态的值设置为auxCoords.auxCoords,因为检查auxCoords的返回,还有另一个auxCoors保存坐标的数组值。

this.setState({ coords: auxCoords.auxCoords });删除渲染中的const { coords } = this.state;和包含贴图对象的{coords && ()}函数。

然后,由于保存多边形坐标的数组现在位于this.state.coords中,因此需要将每个数组数据映射到多边形对象。这将为每个多边形阵列创建一个单独的多边形对象。这将返回handleclick函数中的特定多边形。

下面是一个示例代码和代码片段:

import React, { Component } from "react";
import { Map, Polygon, GoogleApiWrapper } from "google-maps-react";
import data from "./api/coordinates.json";
export class MapContainer extends Component {
state = {
coords: []
};
componentDidMount() {
this.reduceMap();
}
reduceMap = () => {
let auxCoords = {
auxCoords: data.coordinates.reduce(
(a, [c]) => a.concat([c.map(([lat, lng]) => ({ lat, lng }))]),
[]
)
};
this.setState({
coords: auxCoords.auxCoords
});
};
handleClick = (props, polygon, e) => {
let geoJSON = {
type: "Polygon",
coordinates: []
};
const paths = polygon.getPaths().getArray();
for (let path of paths) {
let pathArray = [];
let points = path.getArray();
let firstPoint = false;
for (let point of points) {
if (firstPoint === false) {
firstPoint = point;
}
pathArray.push([point.lng(), point.lat()]);
}
pathArray.push([firstPoint.lng(), firstPoint.lat()]);
geoJSON.coordinates.push(pathArray);
}
console.log("geoJSON", geoJSON);
return geoJSON;
};
render() {
return (
<div>
<Map
google={this.props.google}
style={{ width: "80%", height: "80%", position: "relative" }}
zoom={3}
initialCenter={{ lat: 32.321, lng: -64.757 }}
clickableIcons={false}
className={"map"}
center={{ lat: 32.321, lng: -64.757 }}
>
{this.state.coords.map((poly, key) => (
<Polygon
key={key}
paths={poly}
strokeColor="#0000FF"
strokeOpacity={0.8}
strokeWeight={2}
fillColor="#0000FF"
fillOpacity={0.35}
onClick={this.handleClick}
/>
))}
</Map>
</div>
);
}
}
export default GoogleApiWrapper({
apiKey: "YOUR_KEY"
})(MapContainer);

最新更新