reactjs - 使用 React 在 Google 地图中添加和删除多个多边形 - 让 Refs 正确
问题描述
我正在使用 google-map-react(不是 react-google-maps),并且能够通过在我的主组件中调用函数 polygonDraw 来插入多边形(不使用 drawingManager)。我的函数 polygonDraw 如下所示。
我可以通过在我的 polygonDraw 函数中添加 polygon.setMap(null) 来立即删除最新的多边形。
但问题是: 我无法删除以前添加的多边形或所有多边形。我需要能够删除所有多边形并在不依赖事件处理程序的情况下执行此操作(例如多边形上的单击事件)。
我尝试了不同的方法,但没有成功实施,包括:我无法构造一个多边形组件来呈现新的 google.maps.Polygon({.etc.}) 对象(基于状态/道具)。
因为我能够使用我的 polygonDraw 函数插入多边形,所以我目前对策略的思考是:为每个添加的多边形建立一个参考。我尝试实现 React 引用,包括 Callback refs 和使用 React.createRef。但没有成功。我的 polygonDraw 在主要组件内,但在渲染之外。我不知道是否可以建立和存储对每个添加的多边形的引用,因此可以为每个多边形调用 reference.setMap(null)。如果可能的话,我不知道如何建立引用(构造函数内的代码?polygonDraw 内的代码?渲染内的代码,包括 GoogleMapReact?)
任何帮助/建议表示赞赏:-)
polygonDraw = () => {
let polygonCoords = [{lat: this.state.lat, lng: this.state.lng}, {.etc.}, {.etc.}]
const polygon = new google.maps.Polygon({
paths: [polygonCoords],
fillColor: 'rgb(255, 215, 0)',
});
polygon.setMap(this.state.map.map);
}
render() {
return (
<GoogleMapReact
.etc.
></GoogleMapReact>
)}
解决方案
我不知道它是否会减少性能问题,但是将多边形保存到数组中怎么样。
// You have to create a store (eventually in the state?)
const polygons = [];
polygonDraw = () => {
let polygonCoords = [{lat: this.state.lat, lng: this.state.lng}, {.etc.}, {.etc.}]
const polygon = new google.maps.Polygon({
paths: [polygonCoords],
fillColor: 'rgb(255, 215, 0)',
});
polygon.setMap(this.state.map.map);
// Then use this to save it to the polygons
polygons.push(polygon);
// OR this if you want
polygons.push({identifyer: "foo", polygon});
}
之后,您可以过滤多边形数组并删除您需要的多边形。我不知道这个解决方案是否有效,但你可以试一试:)
推荐阅读
- javascript - 尝试从文件中读取数据时,readFileSync 返回 undefined
- passport.js - 如何使用 NestJS 在 Passport-JS AuthGuard 中操作 cookie?
- javascript - -bash:react-native: command not found ...我想知道如何添加路径 mac 终端
- laravel - 用户没有任何必要的访问权限 Laravel 6
- python - 每次在 django 中生成视图时更新模型
- mysql - Spring JDBC 应用程序中的 SELECT FOR UPDATE 问题
- reactjs - 和有什么区别
和 {我的组件} ? - java - 以编程方式创建的 testng.xml 文件中的层次结构不正确且无法运行
- javascript - 是否可以导入字符串,将其拆分为单词,并仅使用 CSS 将其显示在 3 个不同的堆叠行上?
- ios - 如何正确地将缺少的库和框架添加到现有的 Xcode 项目中