未捕获的TypeError:无法读取属性'国家'未定义的

时间:2018-05-02 16:50:30

标签: javascript geojson topojson

这就是我访问数据的方式:

$.getJSON("https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/meteorite-strike-data.json", 
  function(data){        
    console.log(data);
    states=topojson.feature(data,data.objects.countries).features;
  }
);

但是它给出了错误:Uncaught TypeError: Cannot read property 'countries' of undefined

以下是我的数据示例:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [
          6.08333,
          50.775
        ]
      },
      "properties": {
        "mass": "21",
        "name": "Aachen",
        "reclong": "6.083330",
        "geolocation_address": null,
        "geolocation_zip": null,
        "year": "1880-01-01T00:00:00.000",
        "geolocation_state": null,
        "fall": "Fell",
        "id": "1",
        "recclass": "L5",
        "reclat": "50.775000",
        "geolocation_city": null,
        "nametype": "Valid"
      }
    },

2 个答案:

答案 0 :(得分:1)

您在geojson文件上使用topojson.js。 topojson包含一个名为objects的属性,它包含文件中的功能。 topojson始终以(或至少具有类型"拓扑")开头:

{"type":"Topology",...

你有geojson,geojson经常包含特征集合(或者是类型&#34的单个特征;特征"或类型&#34的几何;多边形","点"等等):

{
  "type": "FeatureCollection",
  "features": [ ... ]
}

由于geojson要素集(或单个要素)没有对象属性,因此您会看到未定义对象时出现的错误。

使用topojson时,topojson.feature()会返回geojson要素集,但由于您已经有geojson要素集,如果要访问这些要素,只需使用:

states = data.features;

注意:此数据集出现在另一个recent question中,geojson与d3一起使用时非常有效,因为有点缺少坐标。在添加坐标之前,您需要过滤掉缺少坐标的点,请参阅此bl.ock和/或链接的问题。

答案 1 :(得分:0)

该API调用返回的JSON上没有objects成员(也没有countries成员):

{
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [
                    6.08333,
                    50.775
                ]
            },
            "properties": {
                "mass": "21",
                "name": "Aachen",
                "reclong": "6.083330",
                "geolocation_address": null,
                "geolocation_zip": null,
                "year": "1880-01-01T00:00:00.000",
                "geolocation_state": null,
                "fall": "Fell",
                "id": "1",
                "recclass": "L5",
                "reclat": "50.775000",
                "geolocation_city": null,
                "nametype": "Valid"
            }
        }
        /* ... */
    ],
    "crs": {
        "type": "name",
        "properties": {
            "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
        }
    }
}