javascript GoogleMap标记不在信息窗口下方

bvhaajcl  于 2023-05-16  发布在  Java
关注(0)|答案(1)|浏览(143)

所以我的谷歌MapAPI标记经常被我的infowindow隐藏,我不知道如何定位infowindow,使它在我的谷歌Map上的标记上方。我以前试过使用css,但它不会移动infowindow,也不会移动标记。
下面是我的Map.js文件代码:

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

function Map() {
  const { isLoaded } = useLoadScript({
    googleMapsApiKey: process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY,
  });

  const location = { lat: -33.81724, lng: 150.99908 };
  const [selectedMarker, setSelectedMarker] = useState(null);

  if (!isLoaded) return <div>Loading...</div>;

  const handleMarkerClick = (marker) => {
    setSelectedMarker(marker);
  };

  return (
    <GoogleMap
      zoom={20}
      center={{ lat: location.lat, lng: location.lng }}
      mapContainerStyle={{
        position: "relative",
        top: 50,
        right: 290,
        width: "230%",
        height: "30vh",
      }}
    >
      <Marker position={location} onClick={() => handleMarkerClick(location)} />
      {selectedMarker && (
        <InfoWindow
          position={selectedMarker}
          anchor={{
            x: 0,
            y: -40,
          }}
          onCloseClick={() => setSelectedMarker(null)}
        >
          <div>
            <h3>ABAD & VILLANUEVA SOLICITOR'S</h3>
          </div>
        </InfoWindow>
      )}
    </GoogleMap>
  );
}

export default Map;
f4t66c6m

f4t66c6m1#

<InfoWindow />组件应该是<Marker></Marker>组件的子组件

代码的标记组件部分:

<Marker position={location} onClick={() => handleMarkerClick(location)} />
  {selectedMarker && (
    <InfoWindow
      position={selectedMarker}
      anchor={{
        x: 0,
        y: -40,
      }}
      onCloseClick={() => setSelectedMarker(null)}
    >
      <div>
        <h3>ABAD & VILLANUEVA SOLICITOR'S</h3>
      </div>
    </InfoWindow>
  )}

请注意,您已将<Marker>组件设置为自关闭,并将/设置在末尾。这意味着<InfoWindow>本身成为一个独立的实体,而不是在<Marker>组件中。这就解释了为什么它看起来像是在试图覆盖标记。

要解决这个问题,您只需将<InfoWindow>组件包含在<Marker>组件中,如下所示:

{/* Change your marker into a non self-closing */}
    <Marker position={location} onClick={() => handleMarkerClick(location)}>
      {selectedMarker && (
        <InfoWindow
          position={selectedMarker}
          anchor={{
            x: 0,
            y: -40
          }}
          onCloseClick={() => setSelectedMarker(null)}
        >
          <div>
            <h3>ABAD & VILLANUEVA SOLICITOR'S</h3>
          </div>
        </InfoWindow>
      )}
      {/* Close the Marker component here to enclose the <InfoWindow />
      Component as a child of the Marker component, and things should
      work fine! */}
    </Marker>

进行更改后,它应该看起来像这样:

这里有一个概念证明片段,如果你想自己检查一下:https://codesandbox.io/s/answer-google-maps-marker-is-not-below-the-infowindow-ub458b?file=/src/Map.js
希望这有帮助!

相关问题