0

我正在尝试在地图上显示(车辆的)位置坐标,其中包含我每 3 秒获取的数据。每次我获取数据(具有“经度”和“纬度”属性的对象数组)时,状态都会更新,我想更新地图上的“标记”以反映车辆的最新位置。

我知道我正在获取数据,但标记没有出现。我循环的方式有问题吗?

class Mapbox extends Component {
  constructor(props){
    super(props)
    this.state = {
      active_vehicles: {},
    };
  }

  componentDidMount() {
    this.interval = setInterval(() => this.fetchData(), 3000);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }


  fetchData = async () => {
    let url = `${request_url}`
    const response = await fetch(url, {
      method: "GET",
      headers: {
        "Accept": "application/json",
      }
    });
    const body = await response.json()
    this.setState({ active_vehicles: body })
  }

  createMarkers = () => {
    let markers = []

    if(this.state.active_vehicles){
      for (let i = 0; i < this.state.active_vehicles.length; i++) {
        markers.push(
        <Marker latitude={this.state.active_vehicles[i]["Latitude"]} longitude={this.state.active_vehicles[i]["Longitude"]}>
          <div>x</div>
        </Marker>
        )
      }
      return markers
    }
  }

  render() {
    return (
      <ReactMapGL
        // mapbox API access token
        mapboxApiAccessToken={MAPBOX_TOKEN}
        mapStyle="mapbox://styles/mapbox/dark-v9"
        {...this.state.viewport}
        onViewportChange={(viewport) => this.setState({viewport})}>

        <div>
          {this.createMarkers()}
        </div>

      </ReactMapGL>
    );
  }
}
4

1 回答 1

1
  1. 更正(在我发表评论后,OP 已更正this.active_vehiclesthis.state.active_vehicles
  2. 向循环key内的 Marker 组件添加属性:for<Maker key={i} ...
于 2018-11-03T21:43:25.017 回答