-1

I'm trying to get the info window of the specific markers to open when the marker is clicked. The map and markers are all appearing correctly and when I hover over a marker it shows the correct title however when I click a marker nothing happens. It's definitely recognizing that the marker was clicked as it logs the message in the console but it just doesn't show the info window. Any help would be greatly appreciated as I've been trying to solve this problem all day.

Thanks

Map.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;

1 Answers1

-1

In the class constructor the initial assignment of this.state = {} is missing property isOpen.

Since you pass that boolean to InfoWindow, is the component's visible prop supposed to do what you think it does? If yes, then the code should kind of work now. If no, you might want to change your code.

Aditionally, every Marker will use the same variable, which means that every related InfoWindow will show up. To solve this you might want to make use of activeMarker you have lying around there in the initial assignment of this.state = {}.

Edit: The InfoWindow won't show because it's nested. Either change Marker component, or move it outside. Documentation here: https://reactjs.org/docs/render-props.html

rbdti
  • 44
  • 6
  • Hi, thanks for trying to help. I've added the isOpen property to this.state and set its initial value to false. However the info window is still not showing. Once I get any of them to show I'll try to focus on getting the right one to show at the intended time. – H.Harrison1993 Apr 09 '20 at 19:14