我在主项目中使用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 时会失去宝贵的开发优势。这个问题与您使用基于类的组件有关。尝试使用功能替代品,因为这最终对我有用。
所以代替标记、多边形或信息窗口
使用 MarkerF、PolygonF 或 InfoWindowF