【问题标题】:create google map with users location with react使用反应创建带有用户位置的谷歌地图
【发布时间】:2018-07-05 22:36:53
【问题描述】:

我是 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

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

非常感谢您的帮助

【问题讨论】:

    标签: javascript reactjs google-maps react-google-maps


    【解决方案1】:

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

    您可以添加一个名为 e.g. 的附加状态。 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);
    

    【讨论】:

    • 还有一个问题 - 为什么您使用 ComponentDidMount 而不是 WillMount?我认为当我想在渲染之前做某事时应该调用 DidMount,据我所知,我在组件渲染后调用 getCurrentLocation ..
    • @arikm9 componentWillMount 在最新版本的 React 中是 UNSAFE。你可以read more about it here。但是,对于您的用例,这并不重要,因为 navigator.geolocation.getCurrentPosition 是异步的,并且在组件安装之前您无法执行任何操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-02
    • 2012-11-25
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多