Google 地图反应仅显示来自状态数组的最后渲染对象的标记

Google maps react only displaying marker of last rendered object from state array

我在从状态数组渲染 google 地图标记时遇到问题。 Only the last rendered marker is shown although all of the markers are listed in react components

我正在使用 google-maps-react 来显示带有许多代表读书俱乐部的标记的位置。我从 rails API 中获取我的标记的地址,将它们循环到地理编码器中并在循环中设置状态。州内的每个对象都有读书俱乐部纬度、经度和数据。

我通过表格收到中心地图位置。表单中的数据通过地理编码器并设置为地图的状态。

当我使用来自 state.markers 的数据添加标记时,只会显示最后一个编码标记。这适用于我循环遍历 state.markers 与否。

import React, { Component } from "react";
import { Map, InfoWindow, Marker, GoogleApiWrapper } from "google-maps-react";

class GoogleMaps extends Component {
  constructor(props) {
    super(props);
    this.state = {
      markers: [],
      lat: null,
      lng: null,
      showingInfoWindow: false,
      activeMarker: {},
      selectedPlace: {}
    };
  }

  componentDidMount() {

    fetch("RAILS API ROUTE", {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer " + sessionStorage.JWT
      }
    })
      .then(e => e.json())
      .then(data => {
        let bookClubs = data.book_clubs;
        console.log("let", bookClubs);
        bookClubs.forEach(club => {
          const googleMapsClient = require("@google/maps").createClient({
            key: "API KEY",
            Promise: Promise
          });
          googleMapsClient
            .geocode({
              address: `${(club.address.address_line1,
              club.address.address_line2,
              club.address.city)}`
            })
            .asPromise()
            .then(response => {
              console.log("response!!!!!!!!!!!!!", response.json.results);
              let info = {
                lat: response.json.results[0].geometry.location.lat,
                lng: response.json.results[0].geometry.location.lng,
                bookClub: club
              };
              let dataCopy = this.state.markers
              dataCopy.push(info);

              this.setState(
                {
                  markers: dataCopy
                },
                () => {
                  console.log("State::::", this.state.markers);
                }
              );
            });
        });

      })
      .catch(error => console.error("Error:", error));
  }

  onMarkerClick = (props, marker, e) =>
    this.setState({
      selectedPlace: props,
      activeMarker: marker,
      showingInfoWindow: true
    });

  onMapClicked = props => {
    if (this.state.showingInfoWindow) {
      this.setState({
        showingInfoWindow: false,
        activeMarker: null
      });
    }
  };



  render() {
    return (
      <div
        style={{ display: "flex", flexDirection: "flexEnd", flexWrap: "wrap" }}
      >




        {this.state.lat != null && (
          <Map
            onClick={this.onMapClick}
            google={this.props.google}
            initialCenter={{
              lng: this.state.lng,
              lat: this.state.lat
            }}
            center={{
              lng: this.state.lng,
              lat: this.state.lat
            }}
            containerStyle={{
              width: "100%",
              height: "250px",
              position: "relative"
            }}
            style={{
              height: "35vh",
              width: "35vh",
              display: "flex",
              justifyContent: "flexEnd"
            }}
            zoom={14}
          >


            {this.state.markers.map((e, i) => (
              <Marker
                key={i}
                onClick={this.onMarkerClick}
                position={{ lat: e.lat, lng: e.lng }}
                title={`${e.bookClub.address.address_line1}  ${e.bookClub.address.address_line2}`}
                name={e.bookClub.address.city}
              />
            ))}

            <InfoWindow
              marker={this.state.activeMarker}
              visible={this.state.showingInfoWindow}
            >
              <div>
                <h1>{this.state.selectedPlace.name}</h1>
              </div>
            </InfoWindow>
          </Map>
        )
        }
      </div>
    );
  }
}
export default GoogleApiWrapper({
  apiKey: "API KEY"
})(GoogleMaps);


问题是我在将数据插入地理编码器时添加了逗号。

 googleMapsClient
            .geocode({
              address: `${(club.address.address_line1,
              club.address.address_line2,
              club.address.city)}

我删除了逗号并编写了如下代码,这解决了我的问题。

googleMapsClient
            .geocode({
              address: `${club.address.address_line1} ${club.address.address_line2} ${club.address.city} `
            })

只显示最后一个标记的原因是当我有逗号时地理编码器给所有标记相同的纬度和经度。这导致它们在同一位置相互覆盖,而最后渲染的标记留在顶部。