我一直在努力解决这个问题并需要一些帮助。
这是将返回给我的JSON示例。我把它分配给一个名为result的变量,所以我可以在我的代码中测试它。我不确定如何伪造JSON被归还给我。
https://dl.dropboxusercontent.com/u/10842024/JSON.js
JSON由两个不同的对象组成,Line和Line2,每个对象由多个路径(折线)特征组成。
我正在尝试创建一个Polyline对象,并使用ESRI JavaScript API将每个对象添加到地图中。以下是Polyline对象的文档:
https://developers.arcgis.com/javascript/jsapi/polyline-amd.html#polyline2
require(["esri/geometry/Polyline"], function(Polyline) {
var polylineJson = {
"paths":[[[-122.68,45.53], [-122.58,45.55],
[-122.57,45.58],[-122.53,45.6]]],
"spatialReference":{"wkid":4326}
};
var polyline = new Polyline(polylineJson);
});
我返回的JSON符合Polyline对象所需的内容:
"features": [
{
"attributes": {
"OBJECTID": 2368
},
"geometry": {
"paths": [
[
[
-123.94500566712864,
45.27071700030354
],
[
-123.9449701393585,
45.27069704962526
],
[
-123.94494162013,
45.27067958572745
],
[
-123.94489725722464,
45.2706251239781
],
[
-123.94489153421517,
45.27054128625377
]
]
]
}
},
但是,如何循环浏览每个要素并将JSON插入到Polyline对象中以使其格式正确?
我知道我错过了一些东西,因为我无法弄明白该怎么做。
答案 0 :(得分:0)
我想那个顺序......
for (var i in result.results)
{
var features = result.results[i].features;
for (var j in features)
{
console.log(features[j].attributes.OBJECTID); // print OBJECTID
var geometry = features[j].geometry.paths;
for (var k in geometry)
{
console.log(geometry[k]); // print paths, arrays of points
var points = geometry[k];
for (var l in points)
console.log(points[l]); // print points
}
}
}
http://jsfiddle.net/e0dxn8ze/2/打开JavaScript控制台,看看会发生什么
答案 1 :(得分:0)
这是我刚刚写的一个未经测试的解决方案。
// Get the JSON string
json_string = whaterver_function_gets_you_the_json();
// Parse JSON into JS
polys = JSON.parse(json_string);
// Loop through polys and create Polyline
polys.features.forEach(function(el) {
new Polyline(el.geometry);
});
编辑:抱歉,我没有看到JSON.js链接。这个解决方案应该仍然可以工作,你只需要调整你正在循环的对象属性。例如:result.results[0].features.forEach(function(el){});
或者如果你需要循环遍历所有结果,你可以为forEachs嵌套。