首页 > 解决方案 > 如何获取 javascript 中每一行的所有坐标?因为我想使用 lat 和 long 在地图上绘制标记

问题描述

我正在关注 youtube 教程,使用此api仅获取每个位置的坐标,以使用 mapbox api 绘制标记。

有人可以请帮助如何获取每个国家/地区的 lang 和 lat 值,以使用它们在 mapbox 中绘制标记。

[0 … 99]
0:
coordinates:
latitude: "33.0"
longitude: "65.0"
__proto__: Object
country: "Afghanistan"
country_code: "AF"
country_population: 29121286
id: 0
last_updated: "2020-04-01T08:09:37.434801Z"
latest:
confirmed: 174
deaths: 4
recovered: 0
__proto__: Object
province: ""
__proto__: Object
1: {id: 1, country: "Albania", country_code: "AL", country_population: 2986952, province: "", …}
2: {id: 2, country: "Algeria", country_code: "DZ", country_population: 34586184, province: "", …}
3: {id: 3, country: "Andorra", country_code: "AD", country_population: 84000, province: "", …}
4: {id: 4, country: "Angola", country_code: "AO", country_population: 13068161, province: "", …}
5: {id: 5, country: "Antigua and Barbuda", country_code: "AG", country_population: 86754, province: "", …}

通过使用此代码

function updateMap(){
    fetch("https://coronavirus-tracker-api.herokuapp.com/v2/locations")
        .then(response=> response.json())
        .then(rsp =>{
           console.log(rsp.locations[0].coordinates);
        });
}

我可以访问第一个位置坐标,因为它的索引是 [0] 但我想访问数组的所有元素,然后在内部坐标对象及其坐标值。

标签: javascriptarraysjson

解决方案


由于locations是一个对象数组,您可以使用它.map()来迭代和细化每个对象。

例如:

function updateMap() {
  fetch('https://coronavirus-tracker-api.herokuapp.com/v2/locations')
    .then(response => response.json())
    .then(data => {
      console.log(data.locations.map(obj => obj.coordinates))
    })
}

推荐阅读