【问题标题】:Google maps react only displaying marker of last rendered object from state array谷歌地图反应只显示状态数组中最后渲染对象的标记
【发布时间】:2020-01-06 17:18:31
【问题描述】:

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

我正在使用 google-maps-react 显示一个位置,其中包含许多代表书友会的标记。我从 Rails API 中获取标记的地址,将它们循环到地理编码器中并在循环中设置状态。州内的每个对象都有 lat、lng 和 data 的 bookclubs。

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

当我使用 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);


【问题讨论】:

  • 您能否提供一个您的读书俱乐部数据样本,或者最好提供一个代码沙盒或 stackBlitz,以便我们可以从我们这边复制它?
  • 我发现了问题。很抱歉没有早点发布这个。我需要在地理编码器中写下不带任何逗号的地址。像这样:地址:${club.address.address_line1} ${club.address.address_line2} ${club.address.city}
  • 酷!感谢您的更新并与社区分享解决方案! :)

标签: ruby-on-rails reactjs google-maps google-maps-markers google-maps-react


【解决方案1】:

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

 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} `
            })

仅显示最后一个标记的原因是,当我有逗号时,地理编码器为所有标记提供了相同的 lat 和 lng。这导致它们都在同一位置相互覆盖,而最后渲染的标记留在顶部。

【讨论】:

    猜你喜欢
    • 2018-11-16
    • 2015-11-10
    • 1970-01-01
    • 2013-04-20
    • 2012-11-07
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多