我将使用我的代码作为参考:
export default class DrawingContainer extends Component {
static propTypes = {
onPolygonComplete: PropTypes.func
};
state = {
drawingMode: 'rectangle'
};
render() {
return (
<DrawingManager
drawingMode={this.state.drawingMode}
onPolygonComplete={polygon => {
this.setState({
drawingMode: ''
}, () => {
if (this.props.onPolygonComplete) {
this.props.onPolygonComplete(convertPolygonToPoints(polygon));
}
});
}}
onRectangleComplete={rectangle => {
this.setState({
drawingMode: ''
}, () => {
if (this.props.onPolygonComplete) {
this.props.onPolygonComplete(
convertBoundsToPoints(rectangle.getBounds())
);
}
});
}}
defaultOptions={{
drawingControl: true,
drawingControlOptions: {
position: window.google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
window.google.maps.drawing.OverlayType.POLYGON,
window.google.maps.drawing.OverlayType.RECTANGLE
]
},
rectangleOptions: polygonOptions,
polygonOptions
}}
/>
);
}
}
因此,我首先尝试在首次绘制后将绘图模式切换到默认拖动模式。
DrawingManager
。我将名为drawingMode
的状态的默认变量设置为'rectangle'
,将其传递给DrawingManager
,然后在函数onRectangleComplete
中将其设置为空字符串,并且它起作用,因为地图最初加载矩形模式。但是一旦我点击其中一个绘图控件,它就永远不会停止绘制,即使该变量被设置为空字符串。所以我认为这里有违反受控制的组件。setDrawingMode
函数。但我尝试在绘图管理器上使用ref
然后转到它的状态,并且能够在那里看到它,但后来我读取变量名DO_NOT_USE_THIS_ELSE_YOU_WILL_BE_FIRED
- 我相信库会阻止这个做法。 那么在完成第一次绘图后,如何使用绘图控件以及将绘图模式更改回默认值?
答案 0 :(得分:0)
所以我只用一个停止渲染DrawingManager的函数设置一个切换
<GoogleMap
defaultZoom={10}
defaultCenter={new google.maps.LatLng(38.9072, -77.0369)}
>
{this.props.creatingPolygon && <DrawingManager
defaultDrawingMode={google.maps.drawing.OverlayType.POLYGON}
defaultOptions={
{
drawingControl: this.props.creatingPolygon,
drawingControlOptions: {
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
this.props.creatingPolygon && google.maps.drawing.OverlayType.POLYGON
],
}
}
}
onPolygonComplete={(polygon) => this.createDeliveryZone(polygon)}
/>}
</GoogleMap>
答案 1 :(得分:0)
handlePolygonComplete(polygon) {
console.log(this);
const paths = polygon.getPath().getArray();
if (paths.length < 3) {
polygon.setPaths([]);
alert("You need to enter at least 3 points.")
} else {
const coords = paths.map((a) => [a.lat(), a.lng()]);
this.setDrawingMode(null);
this.setOptions({ drawingControlOptions: { drawingModes: [] } });
window.addPolygonToState(coords);
}
和
<DrawingManager
onPolygonComplete={this.handlePolygonComplete}
>
在这里,我检查用户是否放置了至少3个点,如果放置了3个点,则获取其坐标并删除绘图模式。