如何解决在 Leaflet 中拖动后获取更新的坐标
我正在使用 react-leaflet 和 Leaflet.Path.Drag 来拖动 GeoJSON。我需要将 GeoJSON 协调保持在 React 状态。问题是 dragEnd
上的更新坐标不正确,拖动后 GeoJSON 位置不正确。
App.js
import React from "react";
import { MapContainer,GeoJSON,TileLayer,useMap } from "react-leaflet";
import "./styles.css";
import "leaflet/dist/leaflet.css";
require("leaflet-path-drag");
export default function App() {
const geoJSONRef = React.useRef(null);
const [coordinates,setCoordinates] = React.useState([
[-104.98569488525392,39.63431579014969],[-104.98569488525392,39.64165260123419],[-104.97161865234376,39.63431579014969]
]);
const handleFeature = (layer) => {
layer.makeDraggable();
layer.dragging.enable();
layer.on("dragend",function (e) {
const latLngs = e.target.getLatLngs()[0];
console.log({ latLngs });
const coordinates = latLngs.map((point) => [point.lng,point.lat]);
geoJSONRef.current.eachLayer((geoLayer) => {
console.log(geoLayer.getLatLngs()[0]);
});
setCoordinates(coordinates);
});
};
const object = {
polygon: {
type: "FeatureCollection",features: [
{
type: "Feature",properties: {},geometry: {
type: "Polygon",coordinates: [[...coordinates]]
}
}
]
}
};
return (
<MapContainer center={[39.63563779557324,-104.99234676361085]} zoom={12}>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.osm.org/{z}/{x}/{y}.png"
/>
<GeoJSON
key={`${coordinates}`}
ref={geoJSONRef}
data={object.polygon}
style={() => ({
color: "green",weight: 3,opacity: 0.5
})}
draggable={true}
pmIgnore={false}
onEachFeature={(feature,layer) => handleFeature(layer)}
></GeoJSON>
</MapContainer>
);
}
解决方法
我不知道为什么,但 e.target._latlngs[0]
和 e.target.getLatLngs()[0];
给出了不同的结果。因此,如果您尝试使用第一个表达式,它会按预期工作,而无需进一步移动拖动的多边形
layer.on("dragend",function (e) {
const latLngs = e.target._latlngs[0]; // here replace the expression
const coordinates = latLngs.map((point) => [point.lng,point.lat]);
geoJSONRef.current.eachLayer((geoLayer) => {
// console.log(geoLayer.getLatLngs()[0]);
});
setCoordinates(coordinates);
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。