Search code examples
javascriptleafletfetchmarkers

Fetching multiple API with correct data


Good afternoon everyone.

I have a small web app which is using API to display bike stations on a map.

I'm using this Bike API

This is my map - Leaflet Maps

Issue: Currently I'm fetching only one API and I take only few parameters from JSON response. But I need to fetch another API as well and take only 2 parameters from it.

This is how my code currently looks like -

import "./styles.css";
import L from "leaflet";
import "leaflet/dist/leaflet.css";

const icon = L.icon({
  iconSize: [25, 41],
  iconAnchor: [10, 41],
  popupAnchor: [2, -40],
  iconUrl: "https://unpkg.com/[email protected]/dist/images/marker-icon.png",
  shadowUrl: "https://unpkg.com/[email protected]/dist/images/marker-shadow.png"
});

var map = L.map("map", {
  preferCanvas: true
}).setView([51.505, -0.09], 3);

L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
  attribution:
    '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);


fetch("https://gbfs.urbansharing.com/oslobysykkel.no/station_information.json")
  .then((responseOne) => responseOne.json())
  .then((responseDataOne) => {
    console.log(responseDataOne.data);
    const stations = responseDataOne.data.stations;

    const layerGroup = L.featureGroup().addTo(map);

    stations.forEach(({ lat, lon, name, address}) => {
      layerGroup.addLayer(
        L.marker([lat, lon], { icon }).bindPopup(
          `${name}, 
           ${address}`
        )
      );
    });

    map.fitBounds(layerGroup.getBounds());
  });

As you can see from this API I'm taking out name and address of the place

I need to use this API - https://gbfs.urbansharing.com/oslobysykkel.no/station_status.json and I'm only interested in this specific parameters (from Docs).

{
 "num_bikes_available": 7,
 "num_docks_available": 5,
},

How I can multiple fetch API and take data from both API's and merge them together, that in the end I will have something like

...
L.marker([lat, lon], { icon }).bindPopup(
      `${name}, 
       ${address},
       ${num_bikes_available},
       ${num_docks_available}`
    )
...

Solution

  • You need to use Promise.all to achieve your goal like this:

    Promise.all([
      fetch(
        "https://gbfs.urbansharing.com/oslobysykkel.no/station_information.json"
      ),
      fetch("https://gbfs.urbansharing.com/oslobysykkel.no/station_status.json")
    ]).then(async ([response1, response2]) => {
      const responseData1 = await response1.json();
      const responseData2 = await response2.json();
    
      const data1 = responseData1.data.stations;
      const data2 = responseData2.data.stations;
    
      // console.log(data1, data2);
    
      const layerGroup = L.featureGroup().addTo(map);
    
      data1.forEach(({ lat, lon, name, address, station_id: stationId }) => {
        layerGroup.addLayer(
          L.marker([lat, lon], { icon }).bindPopup(
            `<b>Name</b>: ${name}
            <br/>
            <b>Address</b>: ${address}
            <br/>
           <b>Number of bikes available</b>: ${
             data2.find((d) => d.station_id === stationId).num_bikes_available
           }
        <br/>
       <b>Number of docs available</b>: ${
         data2.find((d) => d.station_id === stationId).num_docks_available
       }
            `
          )
        );
      });
    
      map.fitBounds(layerGroup.getBounds());
    });
    

    You fetch first both requests. When the responses arrive you loop over the first request data. Using the station_id you can extract from the second's request response data num_bikes_available and num_docks_available and achieve the desired behavior.

    Demo