How to display all received coordinates in React Native?

Viewed 36

I want to display all the coordinates at the same time received via MQTT, but currently the code only displays the newest latitude and longitude pair. Does anyone have any advice?

constructor(props) {
  super(props);
  this.state = {
    coordinates: [
      {latitude: 0, longitude: 0}
    ]
  };
};
componentDidMount() {
  client.on('connect', () => {
    client.subscribe('topic');
  });

  client.on('message', (_topic, message) => {
    var parsedBody = JSON.parse(message.toString());
    var mqttLat = parsedBody["latitude"];
    var mqttLong = parsedBody["longitude"];
    this.setState({
      coordinates: [
        {latitude: mqttLat, longitude: mqttLong}
      ]
    });
  });
};
<View>
  <MapView>
    {this.state.coordinates.map((marker, i) => (
      <Marker
        key = {i}
        coordinate = {{
          latitude: marker.latitude, 
          longitude: marker.longitude
        }}>
      </Marker>
    ))}
  </MapView>
</View>
1 Answers

I guess that the problem is with the way you save your coordinates in the state. If you want to keep more coordinates than just one, push them to the coordinates array instead of overriding previous one.

  client.on('connect', () => {
    client.subscribe('topic');
  });

  client.on('message', (_topic, message) => {
    var parsedBody = JSON.parse(message.toString());
    var mqttLat = parsedBody["latitude"];
    var mqttLong = parsedBody["longitude"];
    this.setState({
      coordinates: [
        ...this.state.coordinates,
        {latitude: mqttLat, longitude: mqttLong}
      ]
    });
  });
};```
Related