0

I am trying to show different locations of stores that exists in a database in the based on user search, but at first i need to center the map using user's current latitude and longitude.

I did set the lat and lng to 0 in the state and updated the state values when the component is mounted.

The problem is, the map component does not re-render when this state value is updated.

import React, { Component } from 'react'
import { Map, GoogleApiWrapper, InfoWindow, Marker } from 'google-maps-react';
import { GeneConsumer } from '../../store';

const mapStyles = {
  width: '100% !important',
  height: '100% !important'
};

class LocationMap extends Component {

  constructor(props) {
    super(props);

    this.state = {
      currentLatLng: {
        lat: 0,
        lng: 0
      },
      showingInfoWindow: false,  //Hides or the shows the infoWindow
      activeMarker: {},          //Shows the active marker upon click
      selectedPlace: {}          //Shows the infoWindow to the selected place upon a marker
    }

  }


  componentDidMount() {
    navigator.geolocation.getCurrentPosition(
      (position)  => {
        this.setState({
          currentLatLng: {
              lat: position.coords.latitude,
              lng: position.coords.longitude
          }
        });
      },
      (error) => {
        this.setState({
          currentLatLng: {
              lat: 6.4494007,
              lng: 3.4498444
          }
        });
      }
    )
  }

  render() {
    console.log(this.state.currentLatLng.lat)
    console.log(this.state.currentLatLng.lng)
    return(
      <GeneConsumer>
        {value => {
              const {locations} = value;

              const displayMarkers = () => {
                  if(!locations){
                      return null;
                  }
                  return locations.map((location, index) => {
                    return <Marker key={index} id={index} position={{
                    lat: location.latitude,
                    lng: location.longitude
                  }}
                    onClick={() => onMarkerClick(location)} 
                    name = {location.name}
                  />
                  })
              }

              const onMarkerClick = (props, marker, e) =>
                this.setState({
                  selectedPlace: props,
                  activeMarker: marker,
                  showingInfoWindow: true
              });

              const onClose = props => {
                if (this.state.showingInfoWindow) {
                  this.setState({
                    showingInfoWindow: false,
                    activeMarker: null
                  });
                }
              };

              return (

                  <Map
                    google={this.props.google}
                    zoom={10}
                    style={mapStyles}
                    initialCenter={{ lat: this.state.currentLatLng.lat, lng: this.state.currentLatLng.lng}}
                  >
                    {displayMarkers()}
                    <InfoWindow
                      marker={this.state.activeMarker}
                      visible={this.state.showingInfoWindow}
                      onClose={onClose()}
                    >
                    <div>
                      <h4>{this.state.selectedPlace.name}</h4>
                    </div>
                    </InfoWindow>
                  </Map>
              );
        }}
      </GeneConsumer>
    );

  }
}

export default GoogleApiWrapper({
  apiKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxx'
})(LocationMap);

1 Answer 1

2

This is by design, updating initialCenter prop does not cause map to re-render:

initalCenter: Takes an object containing latitude and longitude coordinates. Sets the maps center upon loading.

To re-center the map use center prop along with initialCenter prop. The following example demonstrates how to re-center the map on map click event:

class MapExample extends Component {
  state = {
    currentCenter: this.props.center   //default center  
  };

  handleMapClick = (ref, map, ev) => {
    this.setState({ currentCenter: ev.latLng });
  };

  render() {
    return (
      <Map
        google={this.props.google}
        className={"map"}
        initialCenter={this.props.center}
        center={this.state.currentCenter}
        zoom={this.props.zoom}
        onClick={this.handleMapClick}
      >
        <Marker position={this.state.currentCenter} />
      </Map>
    );
  }
}

export default GoogleApiWrapper({
  apiKey: "--YOUR-KEY-GOES-HERE--"
})(MapExample);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.