在谷歌地图的JSON数据中循环

Looping through JSON Data for Google Maps

本文关键字:循环 数据 JSON 谷歌地图      更新时间:2024-05-13

我正在尝试使用访问此JSON(见下文)文件中的数据,如类型、属性等

data = new google.maps.Data();
var json = data.loadGeoJson('insert-url-here');
for (var i=0; i < json.length; i++) {
      var obj = json[i];
      console.log(obj.coordinates);
}

我在for循环Cannot read property 'length' of undefined的第一行遇到一个错误。我想通过读取对象的coordinates值来放大对象。

google.maps.addListener(data, 'click', function () {
  obj.setZoom(10);
}

我做错了什么?

JSON示例:

"features": [{ "type": "Feature", "properties": { "id": 18, "geometry": { "type": "Point", "coordinates": [ -34.397, 150.644 ] } 

要实际检索coordinates属性,需要执行以下操作:

var json = {"features": [{ "type": "Feature", "properties": { "id": 18, "geometry": { "type": "Point", "coordinates": [ -34.397, 150.644 ]}}}]} 
                          
document.write(json.features[0].properties.geometry.coordinates);

这个JSON是如何构建的

object 
    - property -> features (Array, length: 1)
      [ Object
         - property -> properties (Object)
            - property -> geometry (Object)
               - property -> coordinates (Array, length: 2)
      ]
var json = data.loadGeoJson('insert-url-here');

这里的json变量作为未定义的对象返回,从而导致错误。也最好使用另一个变量名

无论何时返回json,都可以使用类似eval()的方法返回javascript对象。以便您可以使用json.features[0].properties.cordinates 访问坐标

这里的功能是一个数组,所以你需要遍历它们