【问题标题】:Info Window not showing on marker click in react-google-maps在 react-google-maps 中单击标记时未显示信息窗口
【发布时间】:2020-07-22 10:43:12
【问题描述】:

我正在尝试在单击标记时打开特定标记的信息窗口。地图和标记都显示正确,当我将鼠标悬停在标记上时,它会显示正确的标题,但是当我单击标记时没有任何反应。它肯定会在记录时识别出该标记已被单击 控制台中的消息,但它只是不显示信息窗口。任何帮助将不胜感激,因为我整天都在努力解决这个问题。

谢谢

地图.js

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


class MyMapComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      fields: [],
      location: {
        lat: 51.5074,
        lng: 0.1278,
      },
      showingInfoWindow: false,
      activeMarker: {},
      selectedPlace: {},
      taxis: [
        {
          companyName: "",
          address1: "",
          address2: "",
          town: "",
          postcode: "",
          phoneNumber: "",
          email: "",
          coords: {
            lat: "",
            lng: "",
          },
          distance: "",
        },
      ],
    };
  }

  async componentDidMount() {
    const { lat, lng } = await this.getcurrentLocation();
    this.setState((prev) => ({
      fields: {
        ...prev.fields,
        location: {
          lat,
          lng,
        },
      },
      currentLocation: {
        lat,
        lng,
      },
    }));
  }

  getcurrentLocation() {
    this.getNearbyTaxis();
    if (navigator && navigator.geolocation) {
      return new Promise((resolve, reject) => {
        navigator.geolocation.getCurrentPosition((pos) => {
          const coords = pos.coords;
          resolve({
            lat: 51.5074,
            lng: 0.1278,
            /*
            lat: coords.latitude,
            lng: coords.longitude,
            */
          });
          console.log(coords.latitude, coords.longitude);
          this.setState({
            location: {
              lat: 51.5074,
              lng: 0.1278,
            },
          });
        });
      });
    }
    return {
      lat: 0,
      lng: 0,
    };
  }
  addMarker = (location, map) => {
    this.setState((prev) => ({
      fields: {
        ...prev.fields,
        location,
      },
    }));
    map.panTo(location);
  };

  getNearbyTaxis = () => {
    axios
      .get(
        `https://api.tfl.gov.uk/Cabwise/search?lat=${this.state.location.lat}&lon=${this.state.location.lng}`
      )
      .then((res) => {
        res.data.Operators.OperatorList.map((taxi) => {
          this.setState({
            taxis: this.state.taxis.concat({
              companyName: taxi.TradingName,
              address1: taxi.AddressLine1,
              address2: taxi.AddressLine2,
              town: taxi.Town,
              postcode: taxi.Postcode,
              phoneNumber: taxi.BookingsPhoneNumber,
              email: taxi.BookingsEmail,
              coords: {
                lat: taxi.Latitude,
                lng: taxi.Longitude,
              },
              distance: taxi.Distance,
            }),
          });
        });
      })

      .then(console.log(this.state.taxis));
  };

  handleToggle = () => {
    console.log("marker clicked");
    this.setState({
      isOpen: true,
    });
    console.log(this.state.isOpen);
  };

  render() {
    return (
      <>
        <button onClick={this.getNearbyTaxis}>Get Taxis</button>
        <Map
          google={this.props.google}
          style={{
            width: "100%",
            height: "100%",
          }}
          initialCenter={this.state.fields.location}
          center={this.state.fields.location}
          zoom={14}
          //onClick={this.onMapClicked}
          key={shortid.generate()}
        >
          {this.state.taxis.length &&
            this.state.taxis.map((taxi) => {
              return (
                <Marker
                  title={taxi.companyName}
                  name={taxi.companyName}
                  position={taxi.coords}
                  onClick={this.handleToggle} // marker ID is the key here.
                  key={shortid.generate()}
                >
                  <InfoWindow
                    key={shortid.generate()}
                    visible={this.state.isOpen}
                    onCloseClick={this.handleToggle}
                  >
                    <div key={shortid.generate()}>
                      <h1 key={shortid.generate()}> hji </h1>
                    </div>
                  </InfoWindow>
                </Marker>
              );
            })}

          <Marker position={this.state.fields.location} />
        </Map>
      </>
    );
  }
}

export default GoogleApiWrapper({
  apiKey: "MY_API_KEY",
})(MyMapComponent);

TaxiList.js

import React, { useState } from "react";
import { Map, GoogleApiWrapper, InfoWindow, Marker } from "google-maps-react";
import MyMapComponent from "./Map";

function TaxiList(props) {
  return (
    <div>
      <MyMapComponent />
    </div>
  );
}

export default TaxiList;

【问题讨论】:

    标签: javascript reactjs google-maps react-google-maps


    【解决方案1】:

    类构造函数中,this.state = {}的初始赋值缺少属性isOpen

    既然您将该布尔值传递给 InfoWindow,那么组件的 visible 属性是否应该按照您的想法执行?如果是,那么代码现在应该可以工作了。如果不是,您可能需要更改代码。

    另外,每个Marker都将使用相同的变量,这意味着每个相关的InfoWindow都会出现。为了解决这个问题,您可能需要使用 activeMarker,您在 this.state = {} 的初始分配中就在附近。

    编辑:InfoWindow 不会显示,因为它是嵌套的。要么改变 Marker 组件,要么把它移到外面。此处的文档:https://reactjs.org/docs/render-props.html

    【讨论】:

    • 您好,感谢您的帮助。我已将 isOpen 属性添加到 this.state 并将其初始值设置为 false。但是信息窗口仍然没有显示。一旦我让他们中的任何一个展示,我将努力专注于让合适的人在预定时间展示。
    猜你喜欢
    • 2012-06-06
    • 2017-10-30
    • 1970-01-01
    • 2018-07-28
    • 2018-04-02
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 2014-02-18
    相关资源
    最近更新 更多