用用户位置创建Google Map并做出反应 [英] create google map with users location with react

查看:79
本文介绍了用用户位置创建Google Map并做出反应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这是我的代码:

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.

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?

非常感谢您的帮助

推荐答案

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

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

您可以添加一个附加状态,例如loading,并且仅在已知用户的地理位置时才呈现.

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

示例

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

这篇关于用用户位置创建Google Map并做出反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆