用react创建用户位置的google map

ari*_*km9 3 javascript google-maps reactjs react-google-maps

我是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);
Run Code Online (Sandbox Code Playgroud)

通过创建具有用户位置的地图,我得到了initialCenter默认状态值。

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

非常感谢您的帮助

Tho*_*lle 5

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);
Run Code Online (Sandbox Code Playgroud)