Search code examples
javascriptgeojson

Loop Through GeoJSON Properties


I am trying to loop through a specific property from a GeoJSON feature, but having some troubles. Here is how I am trying to achieving it on my local server:

$.getJSON('myData.geojson', function(data) {
    for (var i = 0; i < data.length; i++) {
        var obj = data[i];
        console.log(obj.properties[0].ID);
    }
});

Here's a small sample of the data:

"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "ID": 1, "Name": "ABC Cleaner" }, "geometry": { "type": "Point", "coordinates": [ [ [ [ 46.879682, -110.362566 ] } },
{ "type": "Feature", "properties": { "ID": 2, "Name": "Rapid X Cleaner" }, "geometry": { "type": "Point", "coordinates": [ 46.882224, -110.350167] } },
{ "type": "Feature", "properties": { "ID": 3, "Name": "Ace Cleaner" }, "geometry": { "type": "Point", "coordinates": [ 46.885817, -110.338966 ] } } ...

For example, if I want to print all the ID or Name properties, how would I do that?


Solution

  • You need to use the following code in your loop

    $(document).ready(function() {
      $.getJSON('http://f.cl.ly/items/2k3d2Y3X1m0c3f0l3W3f/sample.json',
        function(data) {
          var result = data.objects.myData.geometries;
          for (var i = 0; i < result.length; i++) {
            alert(result[i].properties.ID)
          }
        });
    })