简体   繁体   中英

How to display all received coordinates in React Native?

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>

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}
      ]
    });
  });
};```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM