使用 React 创建 google 包含用户位置的地图

create google map with users location with react

我是 React 的新手,目前正在尝试学习如何使用 react-google-maps 库。试图将用户地理位置显示为地图的 initialCenter

这是我的代码:

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);

为了创建包含用户位置的地图,我得到了 initialCenter 我的默认状态值。

我该如何解决?我什至使用了生命周期功能吗?

非常感谢您的帮助

navigator.geolocation.getCurrentPosition 是异步的,因此您需要使用成功回调并在其中设置用户位置。

您可以添加一个额外的状态片段,例如loading,并且仅在用户的地理位置已知时呈现。

例子

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);