为什么 react-google-maps/api 不显示线和多边形?



我在主项目中使用react-google-maps/api库,但我看不到我在地图上画的线。所以我创建了演示项目,尝试相同的代码。它的工作原理。但是主项目不工作。我查看了react版本、react-dom版本、react-google-maps/api版本。这三个都是相同的版本。在主体工程中;地图和标记来了。但我想画一个容器或线条,它没有显示出来。当我双击时,我得到坐标信息到我的控制台。我得到了真实坐标信息,但看不到线和容器。为什么我在主项目上看不到线?

import React from 'react';
import { GoogleMap, useJsApiLoader, DrawingManager } from '@react-google-maps/api';
const containerStyle = {
width: '800px',
height: '400px'
};
const center = {
lat: -3.745,
lng: -38.523
};
function App() {
const { isLoaded } = useJsApiLoader({
id: 'google-map-script',
googleMapsApiKey: "my_Key"
})
const onLoad = React.useCallback(function callback(map) {
const bounds = new window.google.maps.LatLngBounds(center);
map.fitBounds(bounds);
}, [])
function getPaths(polygon) {
var polygonBounds = polygon.getPath();
var bounds = [];
for (var i = 0; i < polygonBounds.length; i++) {
var point = {
lat: polygonBounds.getAt(i).lat(),
lng: polygonBounds.getAt(i).lng()
};
bounds.push(point);
}
console.log("coordinates", bounds);
}
return isLoaded ? (
<GoogleMap
mapContainerStyle={containerStyle}
center={center}
zoom={10}
onLoad={onLoad}
>
<DrawingManager
defaultDrawingMode={window.google.maps.drawing.OverlayType.POLYGON}
onPolygonComplete={value => getPaths(value)}
defaultOptions={{
drawingControl: true,
drawingControlOptions: {
position: window.google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
window.google.maps.drawing.OverlayType.POLYGON
],
},
polygonOptions: { editable: true }
}}
/>
</GoogleMap>
) : <></>
}
export default App;

检查反应严格模式是否开启。它应该是关闭的。这修正了我的多边形不显示在地图问题

删除React.StrictMode不是修复!这会给你带来更多的麻烦而不是好处。我也有这个问题,当严格模式打开时,绘图UI不渲染,我也无法修复这个问题,但要记住你的应用程序在关闭严格模式时失去了什么。

虽然禁用严格模式有效,但在使用React时,高度不鼓励这样做,因为您会失去宝贵的开发优势。这个问题与您使用基于类的组件有关。尝试使用功能替代方案,因为它最终对我有效。

所以不要用Marker, Polygon或InfoWindow
用Marker, PolygonF或InfoWindow

最新更新