4

I'm new to React and currently trying to learn how to use react-google-maps library. Tried to show a map with users geolocation as the initialCenter of the map.

This is my code:

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

export class MapContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = { userLocation: { lat: 32, lng: 32 } };
  }
  componentWillMount(props) {
    this.setState({
      userLocation: navigator.geolocation.getCurrentPosition(
        this.renderPosition
      )
    });
  }
  renderPosition(position) {
    return { lat: position.coords.latitude, lng: position.coords.longitude };
  }
  render() {
    return (
      <Map
        google={this.props.google}
        initialCenter={this.state.userLocation}
        zoom={10}
      />
    );
  }
}

export default GoogleApiWrapper({
  apiKey: "-----------"
})(MapContainer);

Insted of creating a map with users location I get an initialCenter of my default state values.

How can I fix it? Am I even using the lifecycle function right?

Thank you very much for your help

Tholle
  • 108,070
  • 19
  • 198
  • 189
arikm9
  • 185
  • 1
  • 13

1 Answers1

5

navigator.geolocation.getCurrentPosition is asynchronous, so you need to use the success callback and set the user location in there.

You could add an additional piece of state named e.g. loading, and only render when the user's geolocation is known.

Example

export class MapContainer extends React.Component {
  state = { userLocation: { lat: 32, lng: 32 }, loading: true };

  componentDidMount(props) {
    navigator.geolocation.getCurrentPosition(
      position => {
        const { latitude, longitude } = position.coords;

        this.setState({
          userLocation: { lat: latitude, lng: longitude },
          loading: false
        });
      },
      () => {
        this.setState({ loading: false });
      }
    );
  }

  render() {
    const { loading, userLocation } = this.state;
    const { google } = this.props;

    if (loading) {
      return null;
    }

    return <Map google={google} initialCenter={userLocation} zoom={10} />;
  }
}

export default GoogleApiWrapper({
  apiKey: "-----------"
})(MapContainer);
Tholle
  • 108,070
  • 19
  • 198
  • 189
  • one more question - why did you used ComponentDidMount and not WillMount? I thought that DidMount supposed to be called when I want to do something before the render and as I understand here I'm making a call to getCurrentLocation after the component renders.. – arikm9 Jul 05 '18 at 23:28
  • @arikm9 `componentWillMount` is `UNSAFE` in the latest version of React. You can [read more about it here](https://reactjs.org/docs/react-component.html#unsafe_componentwillmount). For your use case however, it doesn't really matter since `navigator.geolocation.getCurrentPosition` is asynchronous and you can't do anything before the component mounts anyway. – Tholle Jul 05 '18 at 23:30