Как использовать компонент реагирования для отображения Google Maps InfoWindow - PullRequest
0 голосов
/ 29 марта 2019

У меня есть следующий код, я не использую никаких внешних библиотек внутри моего приложения реакции

import React, { Component } from "react";
import MarkerInfo from "./MarkerInfo";
import { render } from "react-dom";

class Map extends Component {
componentDidMount() {
    this.renderMap();
}

renderMarkerInfo = () => {
    return (
    <div id="markerinfo">
        <h1>THis is info marker</h1>
    </div>
    );
};

renderMap = () => {
    loadScript(
    "https://maps.googleapis.com/maps/api/js?key=KEY&callback=initMap"
    );
    window.initMap = this.initMap;
};

initMap = () => {
    var uluru = { lat: -25.363, lng: 131.044 };
    var map = new window.google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: uluru
    });

    var contentString =
    '<div id="content">' +
    '<div id="siteNotice">' +
    "</div>" +
    '<h1 id="firstHeading" class="firstHeading">Uluru</h1>' +
    '<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>" +
    "</div>";

    var infowindow = new window.google.maps.InfoWindow({
    content: contentString
    });

    var marker = new window.google.maps.Marker({
    position: uluru,
    map: map,
    title: "Uluru (Ayers Rock)"
    });
    marker.addListener("click", function() {
    infowindow.open(map, marker);
    });
};

render() {
    return (
    <div id="map">
        <MarkerInfo />
    </div>
    );
}
}

function loadScript(url) {
    var index = window.document.getElementsByTagName("script")[0];
    var script = window.document.createElement("script");
    script.src = url;
    script.async = true;
    script.defer = true;
    index.parentElement.insertBefore(script, index);
}

export default Map;

текущий Я показываю info window с жестко закодированным текстом, я хочу показать его, используя компонент реакции, как я могу это сделать?

я написал другой компонент, всякий раз, когда маркер я хочу, чтобы динамически показать компонент реакции

Заранее спасибо

1 Ответ

0 голосов
/ 01 апреля 2019

Один вариант для рассмотрения будет:

1) для создания экземпляра InfoWindow без установки свойства content на этом этапе:

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

2) и установка или обновление содержимого динамически с помощью InfoWindow.setContent функции , например, после нажатия на маркер:

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

где InfoWindowContent представлен как элемент React, а ReactDOMServer.renderToString функция используется для его преобразования в HTML строка, поскольку InfoWindow.setContent принимает значение содержимого в виде строки:

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>
);

Вот демоверсия

...