简体   繁体   中英

How to iterate through GeoJson Feed for Google Map

So, I have a GeoJson Feed that looks like this

 {
  "type" : "FeatureCollection",
  "features" : [
    {
      "type" : "Feature",
      "geometry" : {
        "type" : "Point",
        "coordinates" : [
          -84.50926612,
          39.1423275
        ]
      },
      "properties" : {
        "name" : "<a href=\"/Things-To-Do/Attractions/cincinnati-zoo-botanical-garden\">Cincinnati Zoo &amp; Botanical Garden</a>",
        "description" : ""
      }
    },
    {
      "type" : "Feature",
      "geometry" : {
        "type" : "Point",
        "coordinates" : [
          -84.495935481675,
          39.095853705988
        ]
      },
      "properties" : {
        "name" : "<a href=\"/Things-To-Do/Attractions/bb-riverboats-thanksgiving-day-cruise\">BB Riverboats Thanksgiving Day Cruise</a>",
        "description" : ""
      }
    }
  ]
}

I am loading it with this function

var attbut = document.getElementById('loadatt');
attbut.addEventListener('click', function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'path-to-GeoJson', true);
xhr.onload = function() {
loadAttractions(this.responseText);
};
xhr.send();
});

And it is loading fine. However I can't seem to get the 'length' property to iterate.

function loadAttractions(results) {
log(results.FeatureCollection.length);
for (var i = 0; i < results.FeatureCollection.length; i++) {
var coords = results.features[i].geometry.coordinates;
var latLng = new google.maps.LatLng(coords[1],coords[0]);
     var marker = new google.maps.Marker({
     position: latLng,
     map: map
     });
}
}     

I have tried results.features.length , and results.FeatureCollection.features.length , the only thing that "works" is results.length , which gives the whole array. Everything else gives an undefined error.

Thanks for any suggestions or help.

As Dalorzo mentions, if you have the results var, results.features.length works with that data for me.

If you have access to underscore.js, there is a method _.size that will give you the number of objects, but it does not appear that you'll need it to grab this.

Here is a fiddle working with results.features.length .

http://jsfiddle.net/dXQeP/

Thanks to everyone who helped. My problem was that I was fetching the JSON as 'text'

loadAttractions(this.responseText);

When I should have been parsing as JSON

var results = JSON.parse(this.responseText);

That made it work. Thanks again to all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM