0

I'm using the google-maps-react library to add a google map with markers that update on state change.

I want to dynamically add markers after fetching locations from Google's place api and storing them in state. I fetch the data, add it to state then call displayMarkers:

displayMarkers = () => {
    this.state.newStations.map((station, index) => {
      let lat = station.geometry.location.lat();
      let lng = station.geometry.location.lng();
      return (
        <Marker
          key={index}
          id={index}
          position={{
            lat: lat,
            lng: lng,
          }}
          onClick={() => console.log("You clicked me!")}
        />
      );
    });
  };

State is being updated but the markers do not appear on the map.

Reading the doc for google-maps-react, it seems to me that marker must be a child of map in order to be overlaid onto the map.

Marker To place a marker on the Map, include it as a child of the component.

Is there any way to return the Marker as a child of Map?

In the google maps API it seems as though you can do this like so:

var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    title: 'Hello World!'
  });

You pass in the value map, which is the map you wish your marker to be attached or overlaid onto. The prop "map" exists in google-maps-react but there doesn't seem to be a property in Marker which accepts map.

Paul Phillips
  • 33
  • 1
  • 6
  • Duplicate of [How to add markers in react-google-maps?](https://stackoverflow.com/questions/44552917/how-to-add-markers-in-react-google-maps) – MrUpsidown May 05 '20 at 17:44
  • It is not a duplicate because that is a different library. I am using fullstack reacts google-maps-react not react-google-maps. – Paul Phillips May 05 '20 at 17:49
  • Also, I don't need to know how to add markers. That is simple enough. Just render Map with child of Marker. I'm trying to dynamically add markers to an existing map. – Paul Phillips May 05 '20 at 18:05
  • Possible duplicate of [Dynamically Adding Markers on google-map-react](https://stackoverflow.com/questions/43937887/dynamically-adding-markers-on-google-map-react) – geocodezip May 05 '20 at 18:30
  • Comment 1) *I am using google-maps-react* - Comment 2) *I'm using react-google-maps* - Better you link to the library you are using and make it clear. – MrUpsidown May 06 '20 at 00:35
  • https://www.npmjs.com/package/google-maps-react – Paul Phillips May 06 '20 at 18:14

1 Answers1

0

You can do it like this in google-maps-react. You need to have an array in the state to hold the results array. Then when fetching Places results, create an array variable then push the result on that arrau variable. You then set the marker array state value as the array variable.

Then inside your Map object, put the Marker object however you need to add condition that will check if the marker array state value is not null and you map each of the marker array state value in the marker object..

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

export class MapContainer extends Component {
  state = {
    center: {
      lat: 40.854885,
      lng: -88.081807
    },
    markers: null,
  };

  fetchPlaces = (mapProps, map) => {
    let coordinates = [];
    const { google } = mapProps;
    const service = new google.maps.places.PlacesService(map);
    var request = {
      location: this.state.center,
      radius: "500",
      query: "restaurant"
    };
    service.textSearch(request, (results, status) => {
      if (status == google.maps.places.PlacesServiceStatus.OK) {
        for (var i = 0; i < results.length; i++) {
          //console.log(results[i]);
          coordinates.push(results[i]);
        }
        this.setState({ markers: coordinates });
      }
    });
  };

  clickMarker = (props, marker) => {
    console.log(props.placeId);
  };

  render() {
    if (!this.props.loaded) return <div>Loading...</div>;

    return (
      <div>
        <Map
          className="map"
          google={this.props.google}
          center={{
            lat: this.state.center.lat,
            lng: this.state.center.lng
          }}
          onReady={this.fetchPlaces}
          style={{ height: "100%", position: "relative", width: "100%" }}
          zoom={8}
        >
          {this.state.markers != null &&
            this.state.markers.map(coords => (
              <Marker
                key={coords.place_id}
                position={coords.geometry.location}
                onClick={this.clickMarker}
                placeId={coords.place_id}
              />
            ))}
        </Map>
      </div>
    );
  }
}
export default GoogleApiWrapper({
  apiKey: "YOUR_API_KEY"
})(MapContainer);```
Pagemag
  • 2,779
  • 1
  • 7
  • 17