下面是我的编码:

const SiteGoogleMap = compose(
withProps({
googleMapURL: `https://maps.googleapis.com/maps/api/js?key=${GOOGLE_MAP_API_KEY}&v=3.exp&libraries=geometry,drawing,places`,
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: `400px` }} />,
mapElement: <div style={{ height: `100%` }} />
}),
withScriptjs,
withGoogleMap
)((props) =>
<GoogleMap
defaultZoom={18}
defaultCenter={{ lat: 3.1314067, lng: 101.6285082 }}
>
{props.isMarkerShown && <Marker position={{ lat: -34.397, lng: 150.644 }} onClick={props.onMarkerClick} />}

<DrawingManager
  defaultDrawingMode={google.maps.drawing.OverlayType.POLYGON}
  defaultOptions={{
    drawingControl: true,
    drawingControlOptions: {
      position: google.maps.ControlPosition.TOP_CENTER,
      drawingModes: [
        google.maps.drawing.OverlayType.POLYGON
      ],
    }
  }}
  onPolygonComplete={(value) => console.log(getPaths())}
/>
</GoogleMap>


我试图获取绘制的多边形的路径,这将为我提供路径的坐标。但是它在console.log上给出了undefined。你们知道为什么吗?

最佳答案

由于onPolygonComplete事件已映射到polygoncomplete类的DrawingManager,因此value参数表示Polygon对象:

onPolygonComplete={(value) => console.log(getPaths())}
                    ^^^^^
                    polygon object


可以传递给getPaths函数:

onPolygonComplete={(value) => console.log(getPaths(value))}


然后可以像这样打印绘制的多边形的坐标:

function getPaths(polygon){
  var coordinates = (polygon.getPath().getArray());
  console.log(coordinates);
}

09-25 17:32