首页 > 解决方案 > 如何仅从地理 json 文件中获取国家/地区名称?

问题描述

我正在尝试从 geojson 文件中获取所有国家/地区的名称,但它似乎不起作用。我应该如何获取所有名称并将它们放入选择标签中?附上geo json的小屏幕截图。我是否必须将其转换为数组才能在 js 中使用它?感谢您在此处输入图片描述

标签: jsongeojson

解决方案


如果您已经将 geojson 存储在变量中,则可以对其进行迭代:

json['countries'].forEach(country => console.log(country))

考虑到这个合成器,你可以用这个解决方案解决你的问题:

name_of_countries = []
your_geojson['features'].forEach(feature => name_of_countries.push(feature['properties']['name']))

console.log(name_of_countries)

对于您的个人需要:

const fillCountriesSelect = (dataFeatures) => {
    divCountries = document.getElementById('countries')
    select = "<select>"
    dataFeatures.forEach(feature => {
        select += feature['properties']['name']
    })
    select += "</select>"
    divCountries.innerHTML = select
}

推荐阅读