如何解决如何在 google-maps-react 中向我的标记添加 InfoWindow?
我尝试将 InfoWindows 添加到我的地图标记(使用 google-maps-react),但它不起作用,我不明白为什么。状态接收经纬度数据。
const InfoPage = ({data}) => {
const [selectedElement,setSelectedElement] = useState(null)
return (
<div className="mapcontainer">
<Map
google={google}
initialCenter={
{
lat: 48.856614,lng: 2.3522219
}
}
zoom={12}>
{data.map((element,index) => {
return (
<Marker
title={element.fields.nom}
position={{
lat : element.fields.geo_point_2d[0],lng: element.fields.geo_point_2d[1]}}
onClick={()=>{setSelectedElement(element)}}
/>
)})}
{selectedElement ? (
<InfoWindow
position={{
lat : selectedElement.fields.geo_point_2d[0],lng: selectedElement.fields.geo_point_2d[1]}}
onCloseClick={()=>{setSelectedElement(null)}}
>
<div>
<h1>info</h1>
</div>
</InfoWindow>) : null }
</Map>
</div>
);
}
解决方法
由于您将单击显示信息窗口的标记,因此您可以使用信息窗口的 marker
参数而不是 position
参数。您还需要使用 InfoWindow 的 visible
参数并将其设置为 true 才能显示。你可以检查这个 simple code 我是怎么做的(我只是使用了 json 文件中的数据)。下面的代码片段:
import React,{ useState } from "react";
import { Map,GoogleApiWrapper,Marker,InfoWindow } from "google-maps-react";
import data from "./data.json";
const InfoPage = () => {
const [selectedElement,setSelectedElement] = useState(null);
const [activeMarker,setActiveMarker] = useState(null);
const [showInfoWindow,setInfoWindowFlag] = useState(true);
return (
<div className="mapcontainer">
<Map
google={google}
initialCenter={{
lat: 39.952584,lng: -75.165221
}}
zoom={8}
>
{data.map((element,index) => {
return (
<Marker
key={index}
title={element.name}
position={{
lat: element.lat,lng: element.lng
}}
onClick={(props,marker) => {
setSelectedElement(element);
setActiveMarker(marker);
}}
/>
);
})}
{selectedElement ? (
<InfoWindow
visible={showInfoWindow}
marker={activeMarker}
onCloseClick={() => {
setSelectedElement(null);
}}
>
<div>
<h1>{selectedElement.name}</h1>
</div>
</InfoWindow>
) : null}
</Map>
</div>
);
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。