使用正确的数据获取多个API

问题描述

大家下午好。

我有一个小型Web应用程序,该应用程序使用API​​在地图上显示自行车站。

我正在使用此Bike API

这是我的地图-Leaflet Maps

问题:目前,我仅获取一个API,并且从JSON响应中获取的参数很少。 但是我也需要获取一个API,并从中仅获取2个参数。

这是我的代码当前的样子-

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

const icon = L.icon({
  iconSize: [25,41],iconAnchor: [10,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_@R_848_404[email protected]")
  .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());
  });

从该API中可以看到,我要取出nameaddress的地方

我需要使用这个API-https://gbfs.urbansharing.com/oslobysykkel.no/station_status.json,我只对这个特定的参数感兴趣(来自文档)。

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

我如何多重获取API并从两个API中获取数据并将它们合并在一起,最终我将拥有类似的东西

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

解决方法

您需要使用Promise.all来实现以下目标:

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());
});

您先获取两个请求。当响应到达时,您将遍历第一个请求数据。使用station_id,您可以从秒的请求响应数据num_bikes_availablenum_docks_available中提取并实现所需的行为。

Demo

,

不确定这是否是最有效的方法,但是您不能只在最后一个.then()中进行第二次提取,然后编写一个函数来合并刚刚提取的两个数据

如此:

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;
    fetch("https://secondapi").then((data) => {
      //write function to merge the 2
    
    const layerGroup = L.featureGroup().addTo(map);

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

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

另外,我目前正在自己​​做一个传单项目,我必须说,如果您使用ReactJs来构建您的网站,react-leaflet真的很有帮助