0

I'm trying to display location coordinates (of vehicles) on a map with data that I'm fetching every 3 seconds. Every time I fetch the data (array of objects with attribute "Longitude" and "Latitude"), the state will update and I want to update the "markers" on a map to reflect the vehicles' latest positions.

I know I'm fetching the data but the markers are not showing up. Is there something wrong with the way I loop?

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>
    );
  }
}
jj008
  • 1,033
  • 3
  • 23
  • 48
  • 1
    I think you meant `this.state.active_vehicles` instead of `this.active_vehicles` in your createMarkers() function. Also this.state.active_vehicles should be declared as an array `[]` instead of an object `{}` in your component constructor. – Rico Chen Nov 03 '18 at 21:23
  • Is `createMarkers` returning the array of values that you expect to see? – Tom Coughlin Nov 03 '18 at 21:33
  • Thanks @RicoChen for correcting my mistakes. Now the markers are showing but I'm getting an error of `Each child in an array or iterator should have a unique "key" prop`. How can I stop that from happening? – jj008 Nov 03 '18 at 21:35
  • Easy, just add that attribute with some unique value, that is ` – Rico Chen Nov 03 '18 at 21:40
  • @RicoChen Thank you! Please submit your answer and I'll accept it. – jj008 Nov 03 '18 at 21:40

1 Answers1

1
  1. Correct this.active_vehicles to this.state.active_vehicles (OP has corrected after I posted my comment)
  2. Add key attribute to the Marker component inside the for loop: <Maker key={i} ...
Rico Chen
  • 2,260
  • 16
  • 18