且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用React组件显示Google Maps InfoWindow

更新时间:2023-10-08 23:35:46

要考虑的一个选项是:

1)在不设置content属性的情况下创建InfoWindow的实例:

1) to create an instance of InfoWindow without setting content property at this stage:

const infowindow = new window.google.maps.InfoWindow({
      content: ""
});

2)和 set update 内容通过

2) and set or update content dynamically via InfoWindow.setContent function once a marker is clicked:

marker.addListener("click", () => {
    const content = ReactDOMServer.renderToString(InfoWindowContent);
    infowindow.setContent(content);
    infowindow.open(map, marker);
});

其中InfoWindowContent表示为React元素,并且 ReactDOMServer.renderToString函数用于将其呈现为HTML 字符串,因为InfoWindow.setContent接受内容值作为字符串:

where InfoWindowContent is represented as a React element and ReactDOMServer.renderToString function is used to render it into HTML string since InfoWindow.setContent accepts content value as a string:

const InfoWindowContent = (
  <div id="bodyContent">
    <p>
      <b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a large sandstone
      rock formation in the southern part of the Northern Territory, central
      Australia. It lies 335&#160;km (208&#160;mi) south west of the nearest
      large town, Alice Springs; 450&#160;km (280&#160;mi) by road. Kata Tjuta
      and Uluru are the two major features of the Uluru - Kata Tjuta National
      Park. Uluru is sacred to the Pitjantjatjara and Yankunytjatjara, the
      Aboriginal people of the area. It has many springs, waterholes, rock caves
      and ancient paintings. Uluru is listed as a World Heritage Site.
    </p>
    <p>
      Attribution: Uluru,
      <a href="https://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">
        https://en.wikipedia.org/w/index.php?title=Uluru
      </a>
      (last visited June 22, 2009).
    </p>
  </div>
);

这是演示