Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create google map with users location with react

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

like image 859
arikm9 Avatar asked Nov 15 '25 05:11

arikm9


1 Answers

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);
like image 159
Tholle Avatar answered Nov 17 '25 17:11

Tholle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!