【问题标题】:Setting initial center for map from Web API on a React / google-maps-react component在 React / google-maps-react 组件上从 Web API 设置地图的初始中心
【发布时间】:2021-02-01 00:27:57
【问题描述】:

我正在使用 google-maps-react 库,并且有一个关于从 Web API 检索纬度/经度坐标以在组件加载时填充地图中心的问题。我可以看到 Web API 调用已成功进行,并使用 console.log() 语句返回了我期望的值,但地图没有用这些值更新。我怀疑这与时间有关,但我不确定问题出在哪里。

我在构造函数和 componentDidMount() 方法中尝试了以下代码。两者都检索值,但都不能通过刷新地图来工作。我想这是我对 React 事件/状态处理的误解:

componentDidMount() {
    const initialBoundingBoxapiUrl = 'https://localhost:44395/api/User/abc';
    fetch(initialBoundingBoxapiUrl)
      .then((response) => response.json())
      .then((data) => {
        console.log('Data returned = ' + data);
        var values = data.split(',');

        // this.state.lat = values[0];
        // this.state.lng = values[1];

        this.setState({lat:  values[0]});
        this.setState({lng:  values[1]});
    });
  }

state = {
    lat: "40.0",
    lng: "-74.0"
  };

我已经尝试过直接更新状态值和使用 setState() 方法。

如果我手动设置“lat”和“lng”状态值,而不是尝试从构造函数或 componentDidMount() 中的 fetch() 方法填充它们,中心将按预期更新。

我的组件如下所示:

  <Map 
    apiKey={'allworkandnoplaymakesscottadullboy'}
    google={this.props.google} 
    initialCenter={{
        lat: this.state.lat,
        lng: this.state.lng
      }}
    zoom={13}>

我的努力在哪里误入歧途?

【问题讨论】:

  • 能否在您的问题中添加sscce

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


【解决方案1】:

看起来地图没有更新到新中心状态的中心的原因是因为您使用的是initialCenter 参数而不是center 参数。如您所见,initialCenter 只会在加载时设置地图的初始中心,这就是为什么它只返回中心状态的初始值。为此,您可以使用center 参数在初始渲染后重新渲染地图。这些都提到了here

作为示例,您可以在使用initialCentercenter 更改componentDidMount 中的中心状态值时看到以下示例代码。

代码片段:

import React, { Component } from "react";
import { Map, GoogleApiWrapper } from "google-maps-react";

export class MapContainer extends Component {
  state = {
    center: {
      lat: 40.854885,
      lng: -88.081807
    }
  };

  componentDidMount() {
    let newLat = {
      lat: 0,
      lng: 0
    };
    this.setState({ center: newLat });
  }
  render() {
    if (!this.props.loaded) return <div>Loading...</div>;

    return (
      <div>
        <div>
          center value: {this.state.center.lat} , {this.state.center.lng}
        </div>
        <Map
          className="map"
          google={this.props.google}
          onClick={this.onMapClicked}
          center={this.state.center}
          style={{ height: "100%", position: "relative", width: "100%" }}
          zoom={8}
        />
      </div>
    );
  }
}
export default GoogleApiWrapper({
  apiKey: "API_KEY"
})(MapContainer);

【讨论】:

    猜你喜欢
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-19
    • 1970-01-01
    • 2022-11-03
    • 2018-11-18
    • 2021-07-20
    相关资源
    最近更新 更多