如何在单击的位置添加标记(react/nextjs Google Maps API)

发布于 2025-02-09 11:03:55 字数 756 浏览 2 评论 0原文

我正在尝试做到这一点,以便当我单击地图时,我可以在鼠标点击的位置上放置标记。 (删除上一个标记)这是我的代码:

const guessCoords = null;

const handleMapClick = (e) => {
  let lat = e.latLng.lat();
  let lng = e.latLng.lng();
  guessCoords = { lat, lng };
};

function Map() {
  const center = useMemo(() => ({ lat: 44, lng: -80 }), []);

  return (
    <GoogleMap
      zoom={10}
      center={center}
      streetView={false}
      mapTypeId="roadmap"
      mapContainerClassName="w-full h-full absolute"
      mapTypeControls={false}
      onClick={(e) => handleMapClick(e)}
    >
      <Marker position={guessCoords} />
    </GoogleMap>
  );
}

我正在使用nextjs。我看了看,没有找到任何用例。

I'm trying to make it so that when I click on the map, I can place a marker on the location of the mouse click. (deleting the previous marker) Here is my code:

const guessCoords = null;

const handleMapClick = (e) => {
  let lat = e.latLng.lat();
  let lng = e.latLng.lng();
  guessCoords = { lat, lng };
};

function Map() {
  const center = useMemo(() => ({ lat: 44, lng: -80 }), []);

  return (
    <GoogleMap
      zoom={10}
      center={center}
      streetView={false}
      mapTypeId="roadmap"
      mapContainerClassName="w-full h-full absolute"
      mapTypeControls={false}
      onClick={(e) => handleMapClick(e)}
    >
      <Marker position={guessCoords} />
    </GoogleMap>
  );
}

I'm using NextJS. I've looked and haven't found anything for my use case.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

|煩躁 2025-02-16 11:03:56

首先,这应该是对您的问题的评论,而不是答案,但Stackoverflow不允许我写评论...所以我尝试以这种方式为您提供帮助!

您正在使用什么组件进行Google Maps集成?我可以向您推荐Google-map-react,对我们有好处。

我建议您修复打字稿代码!
GuessCoords 不应该是const,因为它在您的单击方法中进行了更改。
此代码片段在打字稿中是正确的:

let guessCoords;

const handleMapClick = (e) => {
  const lat = e.latLng.lat();
  const lng = e.latLng.lng();
  guessCoords = { lat, lng };
};

First of all this should be a comment to your question and not an answer but stackoverflow does not allow me to write a comment ... so I try to help you this way!

What component are you using for the Google Maps integration? I can recommend google-map-react to you, works really good for us.

I recommend you to fix your typescript code!
guessCoords should not be const because it is changed in your click method.
This code fragment is correct in typescript:

let guessCoords;

const handleMapClick = (e) => {
  const lat = e.latLng.lat();
  const lng = e.latLng.lng();
  guessCoords = { lat, lng };
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文