我正在尝试使用
react
从开放层地图中绘制的多边形获取坐标点。
我有两个问题
我无法订阅
drawend
因为当我执行我想要触发的功能时甚至不会被触发。当我使用另一个事件时,click
例如我的函数运行?
我无法
event.feature.getGeometry()
从我的多边形中获取实际坐标。我在使用点和点的几何形状时工作,但不是多边形?
例如,当我在地图上订阅
click
事件时,下面的代码有效,我可以获得每个点的几何形状。
import { useEffect, useState } from "react";
export function useWatchOnMapDrawPolygon(mapRef) {
const [polygonCoords, setPolygonCoords] = useState([]);
const onDrawEnd = (event: any) => {
const olMap = event.map;
console.log("event.map inside useWatchOnMapDrawPolygon", olMap);
console.log("olMap.getLayers", olMap.getLayers());
olMap.forEachFeatureAtPixel(event.pixel, (feature: any) => {
const featureId = feature.getId();
const extent = feature?.getGeometry()?.getExtent();
console.log("featureId", featureId); // undefined
console.log("extent", extent); // (4) [119175.69299028325, 175330.0603457574, 155684.03674028325, 201845.0525332574]0: 119175.692990283251: 175330.06034575742: 155684.036740283253: 201845.0525332574length: 4[[Prototype]]: Array(0)
setPolygonCoords(extent); // (4) [119175.69299028325, 175330.0603457574, 155684.03674028325, 201845.0525332574]0: 119175.692990283251: 175330.06034575742: 155684.036740283253: 201845.0525332574length: 4[[Prototype]]: Array(0)
});
};
useEffect(() => {
if (!(mapRef && mapRef.current && mapRef.current.map)) {
return;
}
mapRef.current.map.on("click", onDrawEnd);
() => mapRef.current.map.un("click", onDrawEnd);
}, [mapRef?.current?.map]);
console.log("polygonCoords", polygonCoords);
return polygonCoords;
}
但是当我尝试使用
drawend
事件做同样的事情时,我的函数 onDrawEnd
没有运行并且 event.feature
回来了 undefined
.
在下面的示例中,我正在跟踪
click
事件以强制 onDrawEnd
fn 运行但是我没有得到我想要的数据,这些数据是来自多边形 [[]、[]、...等]
import { useEffect, useState } from "react";
export function useWatchOnMapDrawPolygon(mapRef) {
const [polygonCoords, setPolygonCoords] = useState([]);
const onDrawEnd = (event: any) => {
const olMap = event.map;
console.log("event.map inside useWatchOnMapDrawPolygon", olMap); // [NOTE]: This is the map object,
console.log("olMap.getLayers", olMap.getLayers()); // [NOTE]: This is the layers object
const polygonFeature = event.feature; // [Error]: Event does not have a feature property
const polygonGeometry = polygonFeature.getGeometry(); // [ERROR]: Cannot read property 'getGeometry' of undefined
const polygonCoordinates = polygonGeometry.getCoordinates();
setPolygonCoords(polygonCoordinates); // [ERROR]
};
useEffect(() => {
if (!(mapRef && mapRef.current && mapRef.current.map)) {
return;
}
mapRef.current.map.on("click", onDrawEnd);
() => mapRef.current.map.un("click", onDrawEnd); // [NOTE]: I have tried `drawend` event, but it does not register it for some reason, and yet I can draw on the map. When I change to `click` or `moveend` it runs the onDrawEnd function.
}, [mapRef?.current?.map]);
console.log("polygonCoords", polygonCoords);
return polygonCoords;
}