从API加载geoJSON标记-React Leaflet

时间:2018-10-05 19:26:53

标签: javascript reactjs leaflet geojson react-leaflet

传单,并使用GeoJSON。一旦数据存储在状态中,我试图从获取的GeoJSON API获取标记以呈现在地图上。我尝试使用标记组件显示来自API的标记,但是没有任何内容呈现到页面上。我愿意使用标记组件或任何其他方式来显示标记。谢谢!

import React, { Component } from "react";
import "./App.css";
import { Map, TileLayer, Marker, Popup, GeoJSON } from "react-leaflet";
import L from "leaflet";

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      location: {
        lat: 51.505,
        lng: -0.09
      },
      zoom: 2,
      bikes: null,
      haveUsersLocation: false,
    };

 componentWillMount() {
    fetch(
      "https://bikewise.org:443/api/v2/locations/markers?proximity_square=10"
    )
      .then(response => response.json())
      .then(data => this.setState({ bikes: data }));
  }

 render() {
    const position = [this.state.location.lat, this.state.location.lng];

    return (
      <div className="App">
        <Menu />
        <Map className="map" center={position} zoom={this.state.zoom}>
          <TileLayer
            attribution="&amp;copy <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          />

          <GeoJSON addData={this.state.bikes} /> 

          {this.state.haveUsersLocation ? (
            <Marker position={position} icon={myIcon}>
              <Popup>Your current location</Popup>
            </Marker>
          ) : (
            ""
          )}
        </Map>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

由于this.state.haveUsersLocation始终为false,并且未在组件中的任何位置将其设置为true,因此从未调用Marker组件的原因。如果仅在haveUsersLocation为true时才渲染Marker组件,则需要将haveUsersLocation更改为true以渲染Marker,否则请删除条件

您需要在componentWillMount中将haveUsersLocation设置为true,然后标记将成功呈现

componentWillMount() {
    fetch(
      "https://bikewise.org:443/api/v2/locations/markers?proximity_square=10"
    )
      .then(response => response.json())
      .then(response => this.setState({ haveUsersLocation: true, bikes: response.data.features }));
  }

要强制做出反应以重新呈现GeoJSON数据,您需要将一些data-uniq密钥传递给组件。检查下面的github问题以获取更多详细信息

   <GeoJSON key={`geojson-01`} addData={this.state.bikes} /> 

https://github.com/PaulLeCam/react-leaflet/issues/332#issuecomment-304228071

还需要为标记添加唯一键

   {this.state.haveUsersLocation ? (
        <Marker key={`marker-01`} position={position} icon={myIcon}>
          <Popup>Your current location</Popup>
        </Marker>
      ) :  ""}