如何在 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>
  );
};

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...