首页 > 解决方案 > 映射到 React 中的函数

问题描述

我对反应比较陌生,我正在尝试将位置列表映射到谷歌地图 API。我不知道如何将每个参数传递给谷歌 API 的函数。任何帮助都会很棒。提前致谢。

export class Mapping extends React.Component {

  state = {
    zoom: 1,
  }

  render() {

    Geocode.fromAddress("Eiffel Tower").then(
      response => {
        const { lat, lng } = response.results[0].geometry.location;
        console.log(lat, lng);
      },
      error => {
        console.error(error);
      }
    );

    return (
      <div>
      <Map className="Map" center={[47, -29]} zoom={this.state.zoom}>
        <TileLayer
          attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url="https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}"
        />
        {this.fromAddress}
        {data.features.map((loc, i) => 
          <Marker key={i} position={[
            loc.geometry.coordinates[0],
            loc.geometry.coordinates[1]
          ]}/>
          )}
      </Map>
    </div>
    )
  }
} 

export default Mapping;

标签: javascriptreactjsgoogle-maps

解决方案


考虑将Geocode.fromAddress调用放入componentDidMountmethod,这样一旦位置被解析并保存到state,组件就会重新渲染。

Geocode.fromAddress这是一个示例,它演示了如何显示从方法确定位置的标记 :

class App extends Component {
  state = {
    position: null
  };

  componentDidMount() {
    Geocode.fromAddress("Eiffel Tower").then(
      response => {
        this.setState({position : response.results[0].geometry.location})
      },
      error => {
        console.error(error);
      }
    );
  }

  render() {
    return (
      <Map center={[48.8583736, 2.2922926]} zoom={17}>
        <TileLayer
          attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.osm.org/{z}/{x}/{y}.png"
        />
        {this.state.position && <Marker position={this.state.position} />}
      </Map>
    );
  }
}

推荐阅读