I'm trying to write an application showing current location of stops and trams in my city. Every 5 seconds I fetch data from API in componentDidMount() method and pass it as props to my map component. 1st time I display a map every marker is in its place. However, after 5 seconds my stops markers disappear and only trams markers are in place.
I've already tried fetching in different place, mocking instead of fetching tram data. Also it doesn't matter if I use Google Maps or react-leaflet - result is the same.
App.js:
class App extends Component {
constructor() {
super();
this.state = {};
this.getStops = this.getStops.bind(this);
this.getTrams = this.getTrams.bind(this);
}
componentDidMount() {
this.getStops();
this.getTrams();
setInterval(() => this.getTrams(), 5000);
}
getStops() {
fetch('http://localhost:8080/stopInfo/stops')
.then(response => response.json())
.then(stops => this.setState({ stops: stops.stops }));
}
getTrams() {
fetch('http://localhost:8080/vehicleInfo/vehicles')
.then(response => response.json())
.then(trams => this.setState({ trams: trams.vehicles }));
}
render() {
function normalizeMarker(obj) {
if (obj.latitude !== undefined && obj.longitude !== undefined) {
obj.latitude /= (1000 * 3600);
obj.longitude /= (1000 * 3600);
}
return obj;
}
if (this.state.stops === undefined) {
return ('loading stops...');
}
if (this.state.trams === undefined) {
return ('loading trams...');
}
let trams = this.state.trams.map((tram) => normalizeMarker(tram));
let stops = this.state.stops.map((stop) => normalizeMarker(stop));
return (
<div className="App">
<MapContainer stops={stops} trams={trams}/>
</div>
);
}
MapContainer.js:
export default class MapContainer extends Component {
constructor(props) {
super(props);
this.state = {
lat: 50.0613888889,
lng: 19.9383333333,
zoom: 13
};
}
displayStop(stop) {
return (
<Marker key={stop.id} position={[stop.latitude, stop.longitude]} icon={stopIcon}>
<Popup>
Stop: {stop.name}
</Popup>
</Marker>
);
}
displayTram(tram) {
if (tram.deleted === true) {
return;
}
return (
<Marker key={tram.id} position={[tram.latitude, tram.longitude]} icon={tramIcon}>
<Popup>
Tram: {tram.name}
</Popup>
</Marker>
);
}
render() {
const position = [this.state.lat, this.state.lng];
return (
<Map center={position} zoom={this.state.zoom}>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{this.props.stops.map((stop) => this.displayStop(stop))}
{this.props.trams.map((tram) => this.displayTram(tram))}
</Map>
);
}
}
I've spent a lot of time searching for the solution. Would be great, if someone could help me.