我正在使用google-map-react(而不是react-google-maps),并且能够通过在我的主Component内调用功能polygonDraw(不使用drawingManager)来插入多边形。我的函数polygonDraw可以在下面看到。
我可以通过在我的polygonDraw函数中添加polygon.setMap(null)立即删除最新的多边形。
但是这里是问题:我无法删除之前添加的多边形或所有多边形。我需要能够删除所有多边形,而不必依赖于事件处理程序(就像多边形上的单击事件一样)。
我尝试了不同的方法,但是没有成功实现,包括:我无法构造用于呈现新google.maps.Polygon({。etc。})对象(基于状态/属性)的Polygon组件。
由于我能够使用我的polygonDraw函数插入多边形,所以我目前对策略的想法是:为了为每个添加的多边形建立参考。我尝试实现React参考,包括Callback ref并使用React.createRef。但是没有成功。我的polygonDraw在主要组件内部,但在渲染外部。我不知道是否可以建立和存储对每个添加的多边形的引用,因此可以为每个多边形调用reference.setMap(null)。而且,如果有可能,我不知道如何整理引用(构造函数中的代码?,polygonDraw内部的代码,render包括GoogleMapReact的代码?)
任何帮助/建议均已获悉:-)
polygonDraw = () => {
let polygonCoords = [{lat: this.state.lat, lng: this.state.lng}, {.etc.}, {.etc.}]
const polygon = new google.maps.Polygon({
paths: [],
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: [],
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});
}
[之后,您可以只过滤多边形数组并删除所需的多边形。我不知道此解决方案是否有效,但是您可以尝试一下:)