如何在单击的位置添加标记(react/nextjs Google Maps API)
我正在尝试做到这一点,以便当我单击地图时,我可以在鼠标点击的位置上放置标记。 (删除上一个标记)这是我的代码:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,这应该是对您的问题的评论,而不是答案,但Stackoverflow不允许我写评论...所以我尝试以这种方式为您提供帮助!
您正在使用什么组件进行Google Maps集成?我可以向您推荐Google-map-react,对我们有好处。
我建议您修复打字稿代码!
GuessCoords 不应该是const,因为它在您的单击方法中进行了更改。
此代码片段在打字稿中是正确的:
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: