用jQuery解析GeoJSON文件


9

我试图遍历GeoJSON文件(如下),并最终在“属性”中填充带有一些属性的数组。我会通过找到的各种示例来说明问题。我是否需要嵌入另一个$ .each()才能进入属性。如果不是很明显,我是陌生的,我已经碰壁了。

到目前为止,我有:

$(document).ready(function () {    
            $.getJSON('testpoint.geojson', function (data) {
                var items = [];
                $.each(data.features, function (key, val) {
                    items.push('<li id="' + key + '">' + val + '</li>');
                });
                $('<ul/>', {
                    'class':'my-new-list',
                    html:items.join('')
                }).appendTo('body');
            });
        });

而我的json如下:

{
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "properties": {
                "gid": 1,
                "PID": "9-18-3",
                "BCT": "BCT126",
                "OWNER_TYPE": "A",
                "LOCNO": 0,
                "LOCEXT": "",
                "STREET": "CROSBY LANE",
                "ACQUIRED": "5/7/2010",
                "GRANTOR": "John A. SPARGO",
                "UPLAND": 0,
                "WETLAND": 3.96,
                "TOTAL": 3.96,
                "HABITAT": "salt marsh"
            },
            "geometry": {
                "type": "Point",
                "coordinates": [
                    -70.03209,
                    41.78278
                ]
            }
        }
    ]
}

Answers:


7

你快到了。val.properties的另一个.each应该可以工作:

$.each(data.features, function (key, val) {
    $.each(val.properties, function(i,j){
        items.push('<li id="' + i + '">' + j + '</li>');
    })              
});

2
赛勒斯(Cyrus)感谢,那成功了。我尝试了所有组合,但是那样。我是一个初学者,迭代过程可能会很快变得势不可挡
geomajor56

5

上面写的内容将遍历每个JSON对象中的每个元素。这些是JSON对象,因此您希望将它们视为对象的几何形状和属性,然后简单地使用点符号引用它们。

$.each(data.features, function (key, val) {
  geometry = val.geometry;
  properties = val.properties;
  alert (properties.place);  
});
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.