n.milsht
n.milsht

Reputation: 163

React + Google Maps JS API, dynamically render markers from state

In React, I'm trying to populate my google map with markers where each marker is determined by an array of objects in my state. Right now, if I have a reducedSites array of say 22 objects, only 1-3 of them will render as markers. This seems to be the case no matter how many objects are in state.

Updated

renderMap() {
    const map = document.querySelector('#map')
    this.map = new google.maps.Map(map, {
      center: { lat: this.state.lat, lng: this.state.lng },
      zoom: 8
    });
    const _this = this
    let markers = this.state.reducedSites.map(function(site) {
      return new google.maps.Marker({
        position: {lat: parseInt(site.latitude), lng: parseInt(site.longitude)},
        map: _this.map
      });
    });
  }

Upvotes: 0

Views: 1805

Answers (2)

jfriedman
jfriedman

Reputation: 2181

Change parseInt to parseFloat.

Upvotes: 2

Hadas Zeilberger
Hadas Zeilberger

Reputation: 761

Put <Marker></Marker> component as a child of Map and use your array to set the position property.

  <Map google={this.props.google}
        style={{width: '100%', height: '100%', position: 'relative'}}
        className={'map'}
        zoom={14}>
      <Marker
        name={'SOMA'}
        position={{lat: this.state.markersArray[0].lat, lng: this.state.markersArray[0].lng}} />
     </Marker> 
    </Map>

Make sure to call setState() when changing the values of your positions array so that React automatically renders the DOM each time a value is changed. This is how you get it to render dynamically.

https://github.com/fullstackreact/google-maps-react

Upvotes: 0

Related Questions