地图标记不显示(标记在地图之前呈现)- ReactJS with @react-google-maps/api

Map Marker don't show up (Marker rendered before Map)- ReactJS with @react-google-maps/api

我想要的:

有一个带有 Google 地图的默认 ReactJS 应用程序

问题:

标记不显示

可能原因:

在地图完成加载之前添加了标记。

文件:

App.js,(默认 ReactJS 文件)

Map.js, (自定义 ReactJS 组件)

./style/map.css

Map.js:

import { GoogleMap, useLoadScript, Marker } from "@react-google-maps/api";

import React from "react";
import "./style/map.css";

const Map = ({ zoomLevel, map_lat, map_lng, mark_lat, mark_lng }) => {
  const center = { lat: map_lat, lng: map_lng };

  const { isLoaded } = useLoadScript({
    googleMapsApiKey: "---USE API KEY HERE---",
  });

  //Return maps
  if (!isLoaded) {
    return <div>Loading...</div>;
  } else {
    return (
      <GoogleMap
        mapContainerClassName="map-container"
        zoom={zoomLevel}
        center={center}
        onLoad={() => {
          console.log("Map is loaded!");
        }}
      >
        {/* Debug Purpose */}
        {console.warn("Marker been added!")}

        {/* Add Marker */}
        <Marker position={{ lat: mark_lat, lng: mark_lng }} />
      </GoogleMap>
    );
  }
};

Map.defaultProps = {
  zoomLevel: 14,
  map_lat: 50,
  map_lng: -100,
  mark_lat: 50,
  mark_lng: -100,
};

export default Map;

额外信息:

正如您可能注意到的,根据我的理解,我有控制台日志和警告来告诉渲染顺序,

标记似乎是在地图完全加载之前添加的。

Debug Result: Marker been added before Map onLoad been called.

我确实设法在地图上手动渲染标记(本地主机):

  1. 在运行时间内删除Marker并保存修改,(所以先让Map加载完成。)

  2. 添加标记。 (地图已经完成加载)

现在我得到了标记,但下次不会在这里了。

Manually Add Marker After Map Rendered, The Marker appear.

我终于在网页上渲染了我的标记。

如果您遇到同样的问题,这里是@react-google-maps/api安装文档中的示例代码:

不要问我有什么问题或任何细节,因为我也不知道。

import React from 'react'
import { GoogleMap, useJsApiLoader } from '@react-google-maps/api';

const containerStyle = {
  width: '400px',
  height: '400px'
};

const center = {
  lat: -3.745,
  lng: -38.523
};

function MyComponent() {
  const { isLoaded } = useJsApiLoader({
    id: 'google-map-script',
    googleMapsApiKey: "YOUR_API_KEY"
  })

  const [map, setMap] = React.useState(null)

  const onLoad = React.useCallback(function callback(map) {
    const bounds = new window.google.maps.LatLngBounds(center);
    map.fitBounds(bounds);
    setMap(map)
  }, [])

  const onUnmount = React.useCallback(function callback(map) {
    setMap(null)
  }, [])

  return isLoaded ? (
      <GoogleMap
        mapContainerStyle={containerStyle}
        center={center}
        zoom={10}
        onLoad={onLoad}
        onUnmount={onUnmount}
      >
        { /* Child components, such as markers, info windows, etc. */ }
        <></>
      </GoogleMap>
  ) : <></>
}

export default React.memo(MyComponent)